Javascript DOM HTML Node childNodes Property update second child node

Introduction

Change the background color of the second child node (index 1) of a <div> element:

Click the button to add a background color to the second child node (index 1) of div.

Whitespace inside elements is considered as text, and text is considered as nodes. In this example, index 0, 2 and 4 in DIV are text nodes.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {//from   www  . j a va  2 s .co m
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>
<button onclick="myFunction()">Test</button>

<div id="myDIV">
  <p>First p element</p>
  <p>Second p element</p>
</div>
<script>
function myFunction() {
  var c = document.getElementById("myDIV").childNodes;
  c[1].style.backgroundColor = "yellow";
}
</script>

</body>
</html>



PreviousNext

Related