简体   繁体   English

如何使用childNodes(Javascript)更改元素的内容?

[英]How to change the content of an element with childNodes (Javascript)?

How can I change the content of an element with childNodes (Javascript)? 如何使用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>

 <!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. 首先,应该在标记之后放置脚本标记,否则它将在您要修改的实际html实际呈现之前运行。 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. childNodes是DOM对象的有效属性,但是您在链中有一个错误。 Thirdly, I would use document.querySelector to target elements, not a chain of childNodes . 第三,我将使用document.querySelector来定位元素,而不是childNodes链。 Finally, use innerHTML (not innerHtml) to set html content, or textContent if it is a Text node you are trying to update. 最后,使用innerHTML (而非innerHtml)设置html内容,如果要尝试更新的Text节点,则使用textContent

MDN Docs on innerHTML innerHTML上的MDN文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM