Ali
Ali

Reputation: 99

I've really got confused with children and childNodes in JS

Look at this part of html:

 <table id="Table">
    <tr>
       <td><img src="Sample Pics/Koala.jpg""></td>
       <td><img src="Sample Pics/Desert.jpg"></td>
       <td><img src="Sample Pics/Fall.jpg"></td>
    </tr>

    <tr>
       <td><*img src="Sample Pics/Fish.jpg"></td>
       <td><img src="Sample Pics/Fresh Fruit Platter.jpg"></td>
       <td><img src="Sample Pics/Hydrangeas.jpg"></td>
    </tr>
</table>

I want to change the (for example) *image source via js. i know it would be something like:

document.getElementById("Table").children[?].BlahBlahBlah.src = "New Source";

But i have no idea about it.

Is there some places o learn about children? i looked through W3Schools.com but i found nothing useful.

Upvotes: 0

Views: 143

Answers (2)

Wayne
Wayne

Reputation: 60424

Assuming:

var table = document.getElementById("Table");

Then:

  • table.children returns a live HTMLCollection containing the child elements (HTMLCollection[tbody])

  • table.childNodes returns a NodeList containing all child nodes (including, for example, text nodes, as well as the elements (NodeList[<TextNode textContent="\n ">, tbody]))

You might actually prefer to retrieve the target td more directly:

table.getElementsByTagName("td")[3]

Or even:

table.getElementsByTagName("img")[3]

Upvotes: 0

Bergi
Bergi

Reputation: 665456

I've really got confused with children and childNodes

The difference between them is that while children only contain the child element nodes ("tags"), childNodes also contain text nodes (and a few more, like comments etc). Since many childNodes are empty/whitespace-only text nodes, that property are not very useful for DOM traversal. Use it only if you're really interested in the text.

I want to change the (for example) *image source via js

For tables, there is also the .rows collection that provides convenient access to all rows in the different table sections. Each of those row elements also has a .cells collection, so that you can access your image as

document.getElementById("Table").rows[1].cells[0].children[0]

Upvotes: 2

Related Questions