Display innerHTML of child

2020-07-18 10:46发布

i have:

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

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

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

dosen't work.

标签: javascript
4条回答
SAY GOODBYE
2楼-- · 2020-07-18 11:22

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

查看更多
虎瘦雄心在
3楼-- · 2020-07-18 11:26

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

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

or a safer method

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

[edit 2019] or more modern

document.querySelector("td1 > div").innerHTML
查看更多
太酷不给撩
4楼-- · 2020-07-18 11:34

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

function displayMessage() {
    alert($('#td1 > div').html())
}
查看更多
走好不送
5楼-- · 2020-07-18 11:34

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

查看更多
登录 后发表回答