Output is null, when getting the nodeValue

1.1k Views Asked by At

I'm getting the value of a node by this code in javascript,

function show(){
        var x = document.getElementsByTagName("allowance")[0];
        var y = x.nodeValue;
        alert(y);
    }

from this xml in html.

<xml style="display: none">
        <students id="lul">
            <student>
                <name>Mark Fajardo</name>
                <allowance>9999</allowance>
            </student>
            <student>
                <name>Rencie Macale</name>
                <allowance>20</allowance>
            </student>
        </students>
    </xml>

But the output that alert projects is just null. Help

2

There are 2 best solutions below

1
On BEST ANSWER

Also you can use innerHTML like this

y = document.getElementsByTagName("allowance")[0].innerHTML;
alert(y);
1
On

You should be using textContent to get the text from the XML tag, as nodeValue only returns the text value of a text node in XML, on element nodes, the nodeValue property is always null.

function show() {
  var x = document.getElementsByTagName("allowance")[0];
  var y = x.textContent;
  console.log(y);
}

show()
<xml style="display: none">
  <students id="lul">
    <student>
      <name>Mark Fajardo</name>
      <allowance>9999</allowance>
    </student>
    <student>
      <name>Arabella Raymundo</name>
      <allowance>20</allowance>
    </student>
  </students>
</xml>