1...">

Access element inside div via javascript

I have a div that contains other tags inside it

<div id="mainDiv"> <div> <table> <tbody> <tr> <td>1</td> <td>item</td> <td>item</td> <td>2</td> </tr> </tbody> </table> </div> <div> <table> <tbody> <tr> <td>1</td> <td>item</td> <td>item</td> <td>5</td> </tr> </tbody> </table> </div> </div> 

How can I access the <td> this mainDiv through javascript. I want to change the innerHTML of these <td>

+6
source share
4 answers
 var allDivTd = document.getElementById("mainDiv").getElementsByTagName("TD"); for(var i = 0; i < allDivTd.length; i++){ var td = allDivTd[i]; td.innerHTML = // do something w/ inner html } 
+10
source

Using jQuery: $('div#mainDiv td') will return a set with all the <td> in it.

You can use .html() to change their contents. See http://jsfiddle.net/StuperUser/vD3Tk/ for an example.

Use jQuery if you are doing a lot of JS and have a lot of DOM manipulation. It has a powerful and concise CSS selection syntax, many extension methods for DOM manipulation, and cross-browser compatibility. However, if you make a small amount of JS, then do not feel that it is necessary.

+3
source

You can use document.getElementsByTagName to get all tr tags and then iterate over them to access individual td s

 trs = document.getElementsByTagName('tr'); for (var i = 0; i < tr.length; i++) { var tds = trs[i].childNodes; for (var J = 0; j < tds.length; j++) { var td = tds.childNodes[j]; // process td } } } 

Although, as you can see, it does not look beautiful and rather verbose. For such tasks, it is easier to use a Javascript framework such as jQuery, mootools, dojo .... They support CSS selectors (like jQuery ) that allow you to traverse the DOM with CSS selectors that look like XPath expressions and much more more powerful than manually moving around the house with several functions that Javascript originally provides.

+2
source
 var children = document.getElementById('mainDiv').getElementsByTagName('td'); 
0
source

Source: https://habr.com/ru/post/895058/


All Articles