sami
sami

Reputation: 7645

selecting un-id spans in a div

My markup is a div with 3 spans inside. How can I read the value of each span with jquery.

<div id="mod">
   <span>first span<span>
   <span>second span<span>
   <span>third span<span>
</div>

function getVars(){
  var span1 = ;
  var span2 = ;
  var span3 = ;
}

Upvotes: 0

Views: 73

Answers (5)

Eric Fortis
Eric Fortis

Reputation: 17350

Close the span tags <span> first </span> then it should work, all the answers

another variation

$(document).ready(function () {
    alert($("#mod").children(":first").text());
});

Upvotes: 1

pooja
pooja

Reputation: 2422

<!DOCTYPE html>
<html>
<head>
  <style>
  span { color:#008; }
  span.sogreen { color:green; font-weight: bolder; }
  </style>
  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
  <div>
    <span>John,</span>
    <span>Karl,</span>
    <span>Brandon</span>

  </div>
  <div>
    <span>Glen,</span>
    <span>Tane,</span>
    <span>Ralph</span>

  </div>
<script>
    $("div span:first-child")
        .css("text-decoration", "underline")
        .hover(function () {
              $(this).addClass("sogreen");
            }, function () {
              $(this).removeClass("sogreen");
            });

</script>

</body>
</html>

Upvotes: -1

The Muffin Man
The Muffin Man

Reputation: 20004

You can also use this

$(document).ready(function () {
      alert($("#mod span:eq(0)").html());
    });

Upvotes: 1

mr.b
mr.b

Reputation: 2708

        $(document).ready(function(){
            alert($("#mod span:first").text());//First span child only
            alert($("#mod > span").text());// All span children
        });

Note: Make sure to close your span "".

Upvotes: 1

kobe
kobe

Reputation: 15835

please try this

$('#mod').find('span').text();

Upvotes: 1

Related Questions