javascript - JS get value of generated textnode - Stack Overflow

I have this Javascript in a for loop:renderAElements[i] = document.createElement ("a");render

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?

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?

Share Improve this question asked Jul 1, 2011 at 10:45 YsoL8YsoL8 2,2245 gold badges30 silver badges47 bronze badges 1
  • Use el.nodeValue See this answer stackoverflow./questions/6546924/… – Dennis Plucinik Commented Dec 12, 2012 at 5:06
Add a ment  | 

4 Answers 4

Reset to default 5

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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744311494a4567969.html

相关推荐

  • javascript - JS get value of generated textnode - Stack Overflow

    I have this Javascript in a for loop:renderAElements[i] = document.createElement ("a");render

    7天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信