I got a div, and there i got some childnodes in undefined levels.
Now I have to change the ID of every element into one div. How to realize?
I thought, because they have upgoing IDs, so if the parent is id=’path_test_maindiv’ then the next downer would be ‘path_test_maindiv_child’, and therefore I thought, I’d solve that by wildcards, for example:
JavaScript
x
2
1
document.getElementById('path_test_*')
2
Is this possible? Or are there any other ways?
Advertisement
Answer
Not in native JavaScript. You have various options:
1) Put a class and use getElementsByClassName but it doesn’t work in every browser.
2) Make your own function. Something like:
JavaScript
1
11
11
1
function getElementsStartsWithId( id ) {
2
var children = document.body.getElementsByTagName('*');
3
var elements = [], child;
4
for (var i = 0, length = children.length; i < length; i++) {
5
child = children[i];
6
if (child.id.substr(0, id.length) == id)
7
elements.push(child);
8
}
9
return elements;
10
}
11
3) Use a library or a CSS selector. Like jQuery 😉