I have a tooltip which uses a little bit of non-essential JS.
I want to use JS unobtrusively, apply an id to the tooltip and let JS do it the right way.
The problem is I could need more than one tooltip on a page, and I understand that an id should be uniquely applied.
If there was only ever a maximum of one item per page then this would be simple.
The same could be asked for any button on a page. Imagine I wanted to replace the button with a ‘loading please wait’ image. I would hope to apply an “id=‘please-wait-button’” to any button needing it, multiple times on a page, and let JS do it unobtrusively, but again, I should’t use multiple id’s.
What’s the best way to do this?
What about using getElementByName? Can I apply a name to every tooltip / every button and call it that way? Is that the right way / best way?
Your best bet is probably to use getElementsByClassName(), that way you can select all the elements with (for example) class=“tooltip” and set them up.
You might need to do some hackery for IE versions older than 9 though, something like:
// only load this function in ie 6,7 or 8
function getElementsByClassName(findClass, parent) {
parent = parent || document;
var elements = parent.getElementsByTagName('*');
var matching = [];
for(var i = 0, elementsLength = elements.length; i < elementsLength; i++){
var regex = new RegExp('\\b' + findClass + '\\b')
if (elements[i].className.match(regex)) {
matching.push(elements[i]);
}
}
return matching;
}