javascript 显示孩子的innerHTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5753817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:13:17  来源:igfitidea点击:

Display innerHTML of child

javascript

提问by hhh3112

i have:

我有:

<td id="td1">
     <div>
          aaaaaa
     </div>
</td>

how can i get the innerHTML of the child of "td1" ?

我怎样才能获得“td1”的孩子的innerHTML?

function displaymessage() {
    var i = 0;
    alert(document.getElementById("td1").childNodes[0].innerHTML);
}

dosen't work.

不工作。

回答by KooiInc

Some browsers interpret a line break as the first childNode. So you can do:

一些浏览器将换行符解释为第一个childNode. 所以你可以这样做:

document.getElementById("td1").childNodes[1].innerHTML

or a safer method

或者更安全的方法

document.getElementById("td1").getElementsByTagName('div')[0].innerHTML

[edit 2019] or more modern

[ 2019 年编辑] 或更现代的

document.querySelector("td1 > div").innerHTML

回答by Chris W.

I hate to be the guy that uses jQuery to solve every DOM selection/manipulation problem, but if you used jQueryall you would need is...

我讨厌成为使用 jQuery 来解决每个 DOM 选择/操作问题的人,但是如果您使用jQuery,那么您只需要......

function displayMessage() {
    alert($('#td1 > div').html())
}

回答by Naren Sisodiya

few browser considered whitespace as text node and that create a problem while traversing.

很少有浏览器将空格视为文本节点,这会在遍历时产生问题。

to avoid that you should check the node type

为避免您应该检查节点类型

childNode = document.getElementById("td1").childNodes[0]
if(childNode.nodeType==1)
alert(childNode.innerHTML)

see more information here

在这里查看更多信息

回答by Mahesh KP

try with alert(document.getElementById("td1").childNodes[1].innerHTML);

尝试使用 alert(document.getElementById("td1").childNodes[1].innerHTML);