SharePoint 2010: Finding a Unique HTML ID Using the $get Function




Go look up the definition of the HTML ID attribute. The standards say that the ID must be unique in the page. No two elements should share the same ID.  SharePoint frequently breaks this rule. If you have two web parts of the same, or similar, type, they will often each have elements with the same ID. As an example, any web part in 2010 that displays a document icon (Word, Excel, etc) has an anchor tag like this one: <a id="diidSortDocIcon". As a result, the DOM method getElementById will not work as you might hope. While methods like getElementsByTagName (note the “s”) will return a collection of elements, getElementById (note no “s”) either returns null or the first element found with that ID. Bottom line, unless you loop through all of the elements in the page and check each one for that ID, you will only be able to retrieve the first element that uses that ID.



To deal with this problem, Microsoft added a function to SharePoint with the name $get(). (Actually I believe this $get is part of the AJAX client side libraries.) This function, when passed a single parameter, will return the first element with that ID in the document. When called with an object as the second parameter, it searches all of the child nodes of that object for an element with that ID and returns the first one it finds.

Here’s what the function code looks like when displayed from an alert():




The code displayed above is kind of interesting. If the second parameter is not supplied, then the code just uses getElementById and returns a null or a the single element. If the second parameter is supplied, then the code finds all of the child nodes of the the element listed as the second parameter. It then loops through all of the child elements until it finds one with the ID in the first parameter. (if (a.id == f)


As an example, the following will display the innerHTML of the element with the ID of “diidSortDocIcon”, but only if it is found in the element with the ID of “MSOZoneCell_WebPartWPQ6”.

mywebpart = document.getElementById(“MSOZoneCell_WebPartWPQ6”) $get("diidSortDocIcon", mywebpart).innerHTML


This could also be written as:



$get(), just another little tool for your SharePoint customization toolbox!



No comments:

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.