JS get value of generated textnode

只愿长相守 提交于 2019-12-12 11:08:47

问题


I have this Javascript in a for loop:

renderAElements[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?


回答1:


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

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



回答2:


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



回答3:


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>



回答4:


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



来源:https://stackoverflow.com/questions/6546924/js-get-value-of-generated-textnode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!