gaurav gaurav - 3 months ago 7
HTML Question

Why is previousSibling not working?

this is demo code so I want only follow the pattern that when user click button it show inner text of anchor in

h3
tag .

My Code



var a = document.getElementById('btn');
var b = a.previousSibling.firstChild.innerText;
alert(b);

<div class="box">
<p>This is a paragraph</p>
<h3><a href="#"> Heading </a> </h3>
<button id="btn">Click Me</button>
</div>





I am getting this :

Error is Cannot read property 'innerText' of null

Answer

you need to use previousElementSibling instead

var a = document.getElementById('btn');
var b = a.previousElementSibling.firstChild.innerText;
console.log(b);
<div class="box">
  <p>This is a paragraph</p>
  <h3><a href="#">Heading</a></h3>
  <button id="btn">Click Me</button>
</div>