I’m trying to get the content of a span when a button is clicked. This is the html:
<div class="multiple-result">
<button class="select-location" id="168">Select</button>
<span>Athens, Greece</span>
</div>
<div class="multiple-result">
<button class="select-location" id="102">Select</button>
<span>Athens, Georgia, USA</span>
</div>
I’m trying to get it so that when the button is clicked it will get the value of the span. This is what I’m using:
$('button.select-location').live('click', function(event){
// set the span value
var span_val = $(this).parent("span").html();
alert('selecting...' + span_val);
});
But the alert is always showing: selecting… null
You want to get the parent first, then find the span:
Edit: Ever go back and look at code you wrote 2 years ago and groan, “Why did I do that?”. The above code is awkward. Instead of
.find("> span"), I should have used.children("span").But, what is a child of your parent? A sibling! So, instead of
.parent().children("span"), I should have used.siblings("span").But, looking at the HTML, we don’t even need to dig through the siblings, we know it’s the next sibling:
or just:
By this point, we’re barely using jQuery at all. We could just say:
But, maybe now I’ve swung the pendulum too far the other way?