admin管理员组文章数量:1429067
How can I change the content of an element with childNodes (Javascript)? I tried something but it did not work.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Zitat</title>
<script type="text/javascript">
var htmlNode = document.documentElement;
var emNode = htmlNode.childNodes[1].childNodes[0].childNodes[1].childNodes[1];
emNode.innerHtml = "BBB";
</script>
</head>
<body>
<ul>
<li>Hello World</li>
<li>AAA <em>DDD</em> CCC.</li>
</ul>
</body>
</html>
How can I change the content of an element with childNodes (Javascript)? I tried something but it did not work.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Zitat</title>
<script type="text/javascript">
var htmlNode = document.documentElement;
var emNode = htmlNode.childNodes[1].childNodes[0].childNodes[1].childNodes[1];
emNode.innerHtml = "BBB";
</script>
</head>
<body>
<ul>
<li>Hello World</li>
<li>AAA <em>DDD</em> CCC.</li>
</ul>
</body>
</html>
Share
Improve this question
edited Feb 1, 2016 at 18:08
AsgarAli
2,2112 gold badges21 silver badges32 bronze badges
asked Feb 1, 2016 at 17:41
Hans BaumHans Baum
4111 gold badge9 silver badges17 bronze badges
1
- Is necessary traversing the DOM in the way of your example?, you could use clases or ids for fastest traversing – dexhering Commented Feb 1, 2016 at 17:57
2 Answers
Reset to default 3
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Zitat</title>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
var arrAllListTags = document.querySelectorAll("li");
arrAllListTags[1].childNodes[1].textContent = "BBB";
});
</script>
</head>
<body>
<ul>
<li>Hello World</li>
<li>AAA <em>DDD</em> CCC.</li>
</ul>
</body>
</html>
First of all, the script tag should be placed AFTER the markup, otherwise it will be run before the actual html you are trying to modify is actually rendered. Second of all, I think your selectors are wrong. childNodes
is a valid property of DOM objects, but you have a mistake in your chain. Thirdly, I would use document.querySelector
to target elements, not a chain of childNodes
. Finally, use innerHTML
(not innerHtml) to set html content, or textContent
if it is a Text node you are trying to update.
MDN Docs on innerHTML
本文标签: child nodesHow to change the content of an element with childNodes (Javascript)Stack Overflow
版权声明:本文标题:child nodes - How to change the content of an element with childNodes (Javascript)? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745421925a2657939.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论