Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

output the childNode value in javascript

Tags:

javascript

dom

how can i use js to output the value of a childNode with an alert(); function or creating a new element. for example.. have this:

<ul id="main">
  <li>
   <h2>Alec</h2>
   <p>NX-01</p>
   <p>command: 2151</p>
  </li>
  <li>simple</li> 
  <li>William</li>
</ul>

<script>
var element = document.getElementById("main");
var values = element.childNodes[1].nodeValue; // the text simple this i want to output
alert('the value is:' + values);
</script>
like image 394
Leoh Avatar asked Mar 01 '26 17:03

Leoh


2 Answers

You can use its innerText property:

var element = document.getElementById("main");
var values = element.childNodes[1].innerText;
alert('the value is:' + values);
// Alec NX-01 command: 2151

The above should print all the text contents of the first <li> element (Alec NX-01 command: 2151)

To further refine it and retrieve the value Alec for example, use another .childNodes[1]

var element = document.getElementById("main");
var values = element.childNodes[1].childNodes[1].innerText;
alert('the value is:' + values);

// Alec
like image 152
Michael Berkowski Avatar answered Mar 03 '26 05:03

Michael Berkowski


Use .nodeValue for IE and .textContent for other browsers.

like image 29
Halcyon Avatar answered Mar 03 '26 06:03

Halcyon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!