Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the same level element value in JS?

Tags:

javascript

I faced with the problem with DOM structure in JavaScript.

I have several div elements with class .item

<div class="item">
  <p class="title">Lorem ipfsum</p>
  <p>...</p>
  <a class="bttn">Button</a>
</div>

So, how can I get the text value of .title by clicking on the bttn on the same .item? In JQ it looks like this $(this).parent('.title') but how can I do it in Vanilla JS?

like image 702
Mark Bg Avatar asked Oct 19 '25 01:10

Mark Bg


1 Answers

Remember: jQuery is just JavaScript. It's a convenient layer over the top of some of the messy parts. You can access a nodes parent using .parentNode. Combine that with querySelector and you've got a solution.

document.querySelector('.bttn').addEventListener('click', function() {
  console.log(this.parentNode.querySelector('.title'));
});
<div class="item">
  <p class="title">Lorem ipfsum</p>
  <p>...</p>
  <a class="bttn">Button</a>
</div>
like image 150
Mike Cluck Avatar answered Oct 21 '25 14:10

Mike Cluck