Hans Baum
Hans Baum

Reputation: 411

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

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>

Upvotes: 2

Views: 6661

Answers (2)

AsgarAli
AsgarAli

Reputation: 2211

<!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>

Upvotes: 3

AndyPerlitch
AndyPerlitch

Reputation: 4739

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

Upvotes: 1

Related Questions