Assigning an ID to multiple "placeholding elements"
I have a JavaScript containing a text开发者_开发百科-input and some "placeholders". The script uses a function to display the value entered in the text-input in some placeholders. The problem is, that if I have to assign an ID to every single placeholder it will take a lot of time - I think avoiding duplication and repetition is called DRY
So my question is: How can I (using javascript) "automatically" assign all <span>
-tags inside a certain <div>
-tag with IDs containing a string, which is the same in all spans, and an integer which differs fx:
<div id="foo1"> //assign inside this div
<span id="placeholder1"></span>
<span id="placeholder2"></span>
<span id="placeholder3"></span>
</div>
<span id="foo2"></span> //this is not assigned, it is outside the "foo1"-<div>
I'm sure it can be done in the, is it called DOM, method? I'm not sure but like this:
window.onload = function(){
var foo = new Array();
}
and so on :) The script, I'm using, is to be seen in this post, and in that post you can also see why I'm not using document.getElementsByName("foo")
to select multiple elements and why I am asking for guidance to do this instead :)
function nameElements(div_name, prefix)
{
var div_elem = document.getElementById(div_name);
var spans = div_elem.getElementsByTagName('span');
for (var i = 0; i < spans.length; ++i)
{
spans[i].id = prefix + (i+1);
}
}
Not sure whether the "for (var i..." works in all browsers, but the rest should work in any DOM-compliant browser.
精彩评论