YsoL8
YsoL8

Reputation: 2214

JS get value of generated textnode

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?

Upvotes: 5

Views: 2642

Answers (4)

Subdigger
Subdigger

Reputation: 2193

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

Upvotes: 0

DoctorMick
DoctorMick

Reputation: 6793

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

Upvotes: 1

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53597

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>

Upvotes: 0

Quentin
Quentin

Reputation: 943152

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

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

Upvotes: 5

Related Questions