Khokhar
Khokhar

Reputation: 149

How to get the value of an element by traversing the DOM

I am traversing the DOM in order to get the value of a table data cell. To be more specific, the following bit of traversing:

const nodeLis = target.parentElement.parentElement.childNodes;

gets me a node list that contains:

NodeList 
0 #text " "
1 <td>title1</td>
2 #text " "
3 <td>title2</td>
4 #text " "
5 <td>title3</td>
6 #text " "

Now what I want to do is be able to get the values of the table data cells, specifically 'title1', 'title1' and 'title3'

Now I have tried to index into the childNodes list by doing

console.log(nodeLis[1]);

But this gets me

<td>title1</td>

and I'm not sure how to grab the actual title1 value from it

Upvotes: 0

Views: 163

Answers (3)

wentjun
wentjun

Reputation: 42526

You can use document.querySelectorAll() for that purpose. After that, you can iterate through the NodeList, and use innerHTML to get the individual child node values.

document.querySelectorAll('td').forEach(x => {
  console.log(x.innerHTML);
})
<table>
  <tr>
    <td>Title 1</td>
    <td>Title 2</td>
    <td>Title 3</td>
  </tr>
</table>


EDIT 1: Instead of using innerHTML, you may want to use textContent instead, as explained on this other link I found. Credits to @German for his answer on his post, and @Brilliand for pointing it out the improvements.

Upvotes: 1

German
German

Reputation: 557

console.log(nodeLis[1].textContent);

Upvotes: 1

Dimitri Mockelyn
Dimitri Mockelyn

Reputation: 1545

You can get the content of the element by looking at the innerHTML property

console.log(nodeLis[1].innerHTML);

Upvotes: -1

Related Questions