javascript - getElementsByTagName("tbody") not working. Alternative? - Stack Overflow

I have a <tbody> tag that I want to reach via JS.I get error when trying to get document.body.get

I have a <tbody> tag that I want to reach via JS.

I get error when trying to get document.body.getElementsByTagName("tbody") or document.getElementsByTagName("tbody"). Why?

Fiddle here

html

<tbody>
<tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
</tr>
</tbody>

I have a <tbody> tag that I want to reach via JS.

I get error when trying to get document.body.getElementsByTagName("tbody") or document.getElementsByTagName("tbody"). Why?

Fiddle here

html

<tbody>
<tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
</tr>
</tbody>
Share Improve this question edited Jun 18, 2013 at 9:42 Rikard asked Jun 18, 2013 at 9:35 RikardRikard 7,80513 gold badges60 silver badges99 bronze badges 2
  • 1 Are you sure the DOM is ready when you execute that code? Are you executing it by the <head> tag? Or is it put after the <body> content? – Niccolò Campolungo Commented Jun 18, 2013 at 9:36
  • 1 What error do you get? – Arjan Commented Jun 18, 2013 at 9:37
Add a ment  | 

2 Answers 2

Reset to default 3

Use

document.getElementsByTagName("tbody")

And you need to wrap tbody with table tag.

See the demo.

Firstly, wrap your HTML inside a <table>.

Secondly, concerning your jsFiddle:

var tbodies = document.getElementsByTagName("tbody");
tbodies.style.display = "none";

This will not work. getElementsByTagName returns a list of elements.

If you want to target the first, use:

var tbodies = document.getElementsByTagName("tbody")[0];

or if you want to target all <tbody>'s, loop through every element and apply the styling to each:

for(var i = 0; i < tbodies.length; i++) {
  tbodies[i].style.display = "none";
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744350163a4569925.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信