Reputation: 43
When I click button I want to get h2 value for that what I did is used a variable
var getClassName = $(this).closest('div').attr('class');
Which gave me its parent class, now I have the parent class I am trying to get its h2
, so I have tried
var getH2Val= $('.'+getClassName+' h2').val();
Which gives me undefined value.
<div id="search-7" class="section-1">
<h2>Test head</h2>
<p>test paragraph</p>
<p><a class="testclass" href="#test2"><button>button</button> </a></p>
</div>
<div id="search-8" class="section-1">
<h2>Test head</h2>
<p>test paragraph</p>
<p><a class="testclass" href="#test2"><button>button</button> </a></p>
</div>
Upvotes: 1
Views: 1356
Reputation: 17190
Another approach, more similar to your code would be getting the parent id
attribute (since they should be unique on a document). Note that using class
attribute on the selector won't assure you will match a unique element.
$('button').click(function()
{
var parentID = $(this).closest('div').attr('id');
var h2Text = $('#' + parentID + ' h2').text();
console.log(h2Text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search-7" class="section-1">
<h2>Test head #1</h2>
<p>test paragraph</p>
<p><button>button</button></p>
</div>
<div id="search-8" class="section-1">
<h2>Test head #2</h2>
<p>test paragraph</p>
<p><button>button</button></p>
</div>
Upvotes: 1
Reputation: 337646
Your closest()
logic is correct. However you then need to find()
within that element to retrieve the h2
. Also note that h2
elements do not have a 'value'. To retrieve the text within them use text()
.
Finally note that you cannot place a button
element within an a
, as nested clickable elements are invalid in HTML. As such I removed the a
element in the below example as it's not needed.
$('button').click(function() {
var h2Text = $(this).closest('div').find('h2').text();
console.log(h2Text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search-7" class="section-1">
<h2>Test head #1</h2>
<p>test paragraph</p>
<p><button>button</button></p>
</div>
<div id="search-8" class="section-1">
<h2>Test head #2</h2>
<p>test paragraph</p>
<p><button>button</button></p>
</div>
Upvotes: 5