townie
townie

Reputation: 787

How to grab an element buried inside an element you grabbed?

Hopefully I can explain it well enough. I do

var foo = document.getElementsByTagName('bar');
var len = foo.length;
for(var i=0;i<len;i++){
//Do stuff
}

Inside that for I also want to be able to get an element (specifically a class) that is buried deep within foo[i]. My thought is something like

var whatIWant = document.getElementsByClassName("name").foo[i];

but that doesn't seem to be what I need to do. Am I just not sure on the syntax or do I need to do something completely different?

Upvotes: 1

Views: 313

Answers (2)

Nitzan Tomer
Nitzan Tomer

Reputation: 164467

As far as I'm aware getElementsByClassName is HTML5 (according to this: https://developer.mozilla.org/en/DOM/document.getElementsByClassName) and so using it means that not all browser will support it.

When you grab an Element from the dom, like with document.getElementsByTagName, you get the same method getElementsByTagName and so you can do: foo[i].getElementsByTagName("...") For the collection of desired elements, then you can iterate over that array and search for the matching classes.

Also, I recommend using javascript libraries such as jQuery or MooTools, it will make your life easier.

Upvotes: 2

Marc B
Marc B

Reputation: 360912

You've almost got it:

foo = document.getElementsByTagName('bar');
// foo is now a nodelist of all nodes named 'bar'.

for (i = 0; i < foo.length; i++) {
   bar = foo[i].getElementsByClassName('baz');
   // bar is now a nodelist of all elements with class 'baz' in the dom tree under foo[i].

}

If you were using jquery, it'd be as simple as:

$('bar .baz').each(function() {
   $(this). etc...;
});

Upvotes: 3

Related Questions