Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery get content of span

Tags:

jquery

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

like image 948
Frank Avatar asked Oct 31 '11 21:10

Frank


People also ask

How do you find the content of a span?

Use the textContent property to get the text of a span element, e.g. const text = span. textContent . The textContent property will return the text content of the span and its descendants. If the element is empty, an empty string is returned.

What is span jQuery?

The <span> tag is an inline container used to mark up a part of a text, or a part of a document. The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute. The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is an inline element.


3 Answers

You want to get the parent first, then find the span:

var span_val = $(this).parent().find("> span").html(); 

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").

var span_val = $(this).parent().children("span").html(); 

But, what is a child of your parent? A sibling! So, instead of .parent().children("span"), I should have used .siblings("span").

var span_val = $(this).siblings("span").html();

But, looking at the HTML, we don't even need to dig through the siblings, we know it's the next sibling:

var span_val = $(this).next("span").html();

or just:

var span_val = $(this).next().html();

By this point, we're barely using jQuery at all. We could just say:

var span_val = this.nextSibling.innerHTML;

But, maybe now I've swung the pendulum too far the other way?

like image 184
gilly3 Avatar answered Oct 19 '22 09:10

gilly3


It's not button's parent. div is button's parent and span is children of the div. Try

var span_val = $(this).parent().children("span").html();

instead.

Working demo

like image 1
genesis Avatar answered Oct 19 '22 08:10

genesis


$('button.select-location').live('click', function(event){

  var span_val = $(this).next("span").html();

  alert('selecting...' + span_val);

});
like image 1
Emil Avatar answered Oct 19 '22 08:10

Emil