danwoods
danwoods

Reputation: 4907

traversing a table with javascript DOM

I know this is the simplest problem ever, but I can't seem to find the answer and I'm searching in the dark, so a little help is appreciated. I'm trying to get the text in the node where class='song_artist'. I have a reference to the parent node, but just can't get to the text I'm looking for. My html looks like this:

<tr id='0000moe2008-05-23d01t01_vbr' class='row-even'><td class='song_name'>Captain America<h3> (00:00)</h3></td><td class='song_artist'>moe.</td><td class='song_date'>2008-05-23</td><td class='song_location'>Jones Beach, VA</td></td><td class='song_extras'></td></tr>  
<tr id='00011-01_Rock_And_Roll_Part_2' class='row-odd'><td class='song_name'>Rock and Roll part 2<h3> (00:00)</h3></td><td class='song_artist'>Phish</td><td class='song_date'>1998-11-20</td><td class='song_location'>Jones Beach, VA</td></td><td class='song_extras'></td></tr>  
<tr id='00021-03_Quinn_The_Eskimo' class='row-even'><td class='song_name'>Quinn the Eskimo<h3> (00:00)</h3></td><td class='song_artist'>Phish</td><td class='song_date'>1998-11-20</td><td class='song_location'>Jones Beach, VA</td></td><td class='song_extras'></td></tr>  

and like I said, I have a reference to the <tr> but can't make it to the <td> I'm looking for. I assume the complete reference looks like: parent.firstChild.nextSibling.data but I keep getting all kinds of dead ends with that. Any javascript gurus on here?

Upvotes: 0

Views: 3235

Answers (2)

Kenan Banks
Kenan Banks

Reputation: 211942

In pure Javascript:

var elements = document.getElementsByClassName('song_artist')
for (var i=0; i<elements.length; i++){
    text = elements[i].innerHTML;
}

Standard caveat: Use a javascript framework instead.

Upvotes: 1

Artem Barger
Artem Barger

Reputation: 41222

You can do:

var collection = document.getElementsByTagName( "td");
for( var i = 0; i < collection.length; ++i)
{
      if ( collection[i].getAttribute("class") === "whateveryouwant")
       {
       }
}

But my advise to switch using javascript framework like jquery, since then only thing you will need to to do is:

var element = $( "td.song_artist") //here you get all element you are looking for

Upvotes: 5

Related Questions