Coder Perfect

Using jQuery, how do I obtain the value of a span?


This is basic.

How can I acquire the above span’s value of ‘This is my name’?

<div id='item1'>
<span>This is my name</span>

Asked by Felipe Barreiros

Solution #1

This, in my opinion, should be a straightforward example:

$('#item1 span').text();


$('#item1 span').html();

Answered by Lewis

Solution #2

$("#item1 span").text();

Answered by rahul

Solution #3

If you want it to say id=”item1,” you’ll need to change it.

$('#item1 span').text()

Answered by Rich

Solution #4

For id=”item1″ you can use $(‘#item1’).text() or $(‘#item1’).html().

Answered by dipraj.shahane

Solution #5

I’m assuming a class is being used because you didn’t supply an attribute for the ‘item’ value:

<div class='item1'>
  <span>This is my name</span>

alert($(".item span").text());

To use your code, be sure to wait for the DOM to load, which you can do with the ready() function in jQuery:

  <title>jQuery test</title>
  <!-- script that inserts jquery goes here -->
  <script type='text/javascript'>
    $(document).ready(function() { alert($(".item span").text()); });
 <div class='item1'>
   <span>This is my name</span>

Answered by Francisco Aquino

Post is based on