Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById() wildcard

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:

document.getElementById('path_test_*') 

Is this possible? Or are there any other ways?

like image 649
Florian Müller Avatar asked Nov 25 '10 08:11

Florian Müller


2 Answers

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:

function getElementsStartsWithId( id ) {   var children = document.body.getElementsByTagName('*');   var elements = [], child;   for (var i = 0, length = children.length; i < length; i++) {     child = children[i];     if (child.id.substr(0, id.length) == id)       elements.push(child);   }   return elements; } 

3) Use a library or a CSS selector. Like jQuery ;)

like image 154
joksnet Avatar answered Sep 22 '22 11:09

joksnet


In one of the comments you say:

(...) IE is anyway banned on my page, because he doesn't get it with CSS. It's an admin tool for developer, so only a few people, and they will anyway use FF

I think you should follow a different approach from the beginning, but for what it's worth, in the newer browsers (ok, FF3.5), you can use document.querySelectorAll() with which you can get similar results like jQuery:

var elements = document.querySelectorAll('[id^=foo]'); // selects elements which IDs start with foo 

Update: querySelectorAll() is only not supported in IE < 8 and FF 3.0.

like image 26
Felix Kling Avatar answered Sep 25 '22 11:09

Felix Kling