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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With