jQuery Selector How to - Select first UL li item with a span inside








Question

We would like to know how to select first UL li item with a span inside.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--from   www .  j  a  va2s . c  om-->
    var itemName = $('ul li:first').find('a span').text();
    console.log(itemName)
});
</script>
</head>
<body>
  <ul>
    <li><a href="#"><span>item1</span></a></li>
    <li><a href="#"><span>item2</span></a></li>
  </ul>
</body>
</html>

The code above is rendered as follows: