How do I get a value of a <span> using jQuery?

This is basic.

How do I get the value 'This is my name' of the above span?

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

I think this should be a simple example:

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

or

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

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

Assuming you intended it to read id="item1", you need

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

$('#item1').text(); or $('#item1').html(); works fine for id="item1"


Since you did not provide an attribute for the 'item' value, I am assuming a class is being used:

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

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

Make sure you wait for the DOM to load to use your code, in jQuery you use the ready() function for that:

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