admin管理员组

文章数量:1401631

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

本文标签: javascriptJS get value of generated textnodeStack Overflow