Reputation: 23
I'm trying to select the header text for a clicked item using jquery/javascript. I'm having an issue writing the proper selectors given the fact that the item clicked isn't a descendant of the header section. For example, if I click item3.1, I want it to return the text "Header 3".
<section class="mainclass">
<section class="header">Header 1</section>
<ul>
<li>item1.1</li>
<li>item1.2</li>
<li>item1.3</li>
</ul>
<section class="header">Header 2</section>
<ul>
<li>item2.1</li>
<li>item2.2</li>
<li>item2.3</li>
</ul>
<section class="header">Header 3</section>
<ul>
<li>item3.1</li>
<li>item3.2</li>
<li>item3.3</li>
</ul>
<section class="header">Header 4</section>
</section>
Current code example:
jQuery('body').on('click','li',function(e) {
if (jQuery(this).parent('header').length <= 0){
alert(jQuery(this).closest('mainclass').find('header').text());
}
});
This code sample returns all the headers. I haven't been able to get this to work with variants of closest, parents, find, etc.
Upvotes: 2
Views: 48
Reputation: 780724
Use .prev()
to get the element just before a selection. So go up to the <ul>
, then go back one element to get the header. Also, you need a .
to match a class.
jQuery('body').on('click', 'li', function(e) {
console.log(jQuery(this).closest('ul').prev('.header').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="mainclass">
<section class="header">Header 1</section>
<ul>
<li>item1.1</li>
<li>item1.2</li>
<li>item1.3</li>
</ul>
<section class="header">Header 2</section>
<ul>
<li>item2.1</li>
<li>item2.2</li>
<li>item2.3</li>
</ul>
<section class="header">Header 3</section>
<ul>
<li>item3.1</li>
<li>item3.2</li>
<li>item3.3</li>
</ul>
<section class="header">Header 4</section>
</section>
Upvotes: 3