Trying to use one click function for all of my div boxes. Did some research but still not able to get it working correctly. I’m new to programming so I might be going about this the wrong way, here is an example of what I’m trying to do:
<div id="test_1">
<p class="example">display this text 1</p>
</div>
<div id="test_2">
<p class="example">display this text 2</p>
</div>
<div id="test_3">
<p class="example">display this text 3</p>
</div>
$('div[id^="test"]').each(function(){
$(this).click(function(){
test = $(this).parent().find('.example').attr("p")
alert(test)
})
})
I thought this would work but if I click on div test 2 or 3 the alert shows "display this text 1" instead of "display this text 2" or "...3".
Any idea what I’m doing wrong?
Remove
.parent(). Otherwise you’re getting all the nested.exampleelements, and retrieving the.attr('p')of the first one.Or shortened like this:
Your question shows that you’re getting a proper text result, though your code shows
.attr("p"), which would not. I’ve left it the way it was to keep the code example the same.