Javascript DOM HTML Element firstElementChild Property get text of first element

Introduction

Get the text of the first element node of a <select> element:

var x = document.getElementById("mySelect").firstElementChild.text;

Click the button to get the text of the first child element of the select element.

View in separate window

<!DOCTYPE html>
<html>
<body>
<select id="mySelect" size="4">
  <option>Python</option>
  <option>CSS</option>
  <option>C++</option>
  <option>Javascript</option>
  </select>
<br><br>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {//from  www.  j a  v  a 2  s.c  o m
  var x = document.getElementById("mySelect").firstElementChild.text;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>



PreviousNext

Related