开发者

JS get value of generated textnode

开发者 https://www.devze.com 2023-03-17 03:35 出处:网络
I have this Javascript in a for loop: renderAEle开发者_JS百科ments[i] = document.createElement (\"a\");

I have this Javascript in a for loop:

renderAEle开发者_JS百科ments[i] = document.createElement ("a");
        renderAElements[i].setAttribute("href", "#");
        renderAElements[i].setAttribute("class", "expander");
        renderAElements[i].appendChild(expand);

        alert (renderAElements[i].nodeValue);

where expand is created as:

var expand = document.createTextNode("+");

The alert, which is meant to return the link text of each created element returns null. Why is this?


Because you are trying to get the nodeValue of the Element node and not the Text node.

alert (renderAElements[i].firstChild.nodeValue);


It's because the a element contains another element and not a value. If you want to get the text out of the node you'll need to do either

renderAElements.childNodes[0].nodeValue

or

renderAElements.innerText


Check this out

<head>
    <script type="text/javascript">
        function GetTextNode () {
            var textContainer = document.getElementById ("textContainer");
            var textNode = textContainer.firstChild;
            alert (textNode.data);
        }
    </script> 
</head>
<body>
    <div id="textContainer">This is a simple text in the container.</div>
    <button onclick="GetTextNode ()">Get the contents of the container</button>
</body>


try this alert (renderAElements[i].firstChild.nodeValue);

0

精彩评论

暂无评论...
验证码 换一张
取 消