How to select of the with javascript?
前端 未结 6 896
忘了有多久
忘了有多久 2020-12-15 22:35

I know this is very easy question, but I couldn\'t find the answer anywhere. Only answers are the ones using jQuery, not pure JS. I\'ve tried the code below and it doesn\'t

6条回答
  •  时光取名叫无心
    2020-12-15 23:11

    This d = t.getElementsByTagName("tr") and this r = d.getElementsByTagName("td") are both arrays. The getElementsByTagName returns an collection of elements even if there's just one found on your match.

    So you have to use like this:

    var t = document.getElementById("table"), // This have to be the ID of your table, not the tag
        d = t.getElementsByTagName("tr")[0],
        r = d.getElementsByTagName("td")[0];
    

    Place the index of the array as you want to access the objects.

    Note that getElementById as the name says just get the element with matched id, so your table have to be like

and getElementsByTagName gets by the tag.

EDIT:

Well, continuing this post, I think you can do this:

var t = document.getElementById("table");
var trs = t.getElementsByTagName("tr");
var tds = null;

for (var i=0; i

Try it!

提交回复
热议问题