helloWhen...">

How to get the first span element of a div class and change

I have a div with a range

<div id="div1"> <span class="">hello</span> </div> 

When I click on a div, I want to change the class of only the first span div element

 $('#div1').click(function() { // ... check if first span element inside the div .. if there and change the class.. }); 
+8
jquery
source share
5 answers
 $('#div1').click(function() { $('span:first', this).prop('class', 'newClassName'); }) 

http://api.jquery.com/first-selector/

http://jsfiddle.net/BUBb9/1/

+17
source share

use

  $("div span:first-child") 

in the following way:

 $('#div1').click(function() {    $('span:first', this).prop('class', 'ClassName'); }) 

contact http://api.jquery.com/first-child-selector/

+5
source share
 $('#div1').click(function(){ var v = $(this).find('span').text(); }); 

Similarly, you can get the span value.

You can also use .html () instead of the .text () method.

+3
source share

Several answers are valid. My approach:

 $('#div1').click(function() { $(this).find('span').first().attr('class','newClassName'); }); 
+1
source share
 $('#div1').click(function() { $('#div1 span:first').attr('class', 'newClassName'); }); 
+1
source share

All Articles