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
user1184100
source share5 answers
$('#div1').click(function() { $('span:first', this).prop('class', 'newClassName'); }) +17
Andreas Wong
source shareuse
$("div span:first-child") in the following way:
$('#div1').click(function() { $('span:first', this).prop('class', 'ClassName'); }) +5
Hemant metalia
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
Hiren h patel
source shareSeveral answers are valid. My approach:
$('#div1').click(function() { $(this).find('span').first().attr('class','newClassName'); }); +1
Khรดi
source share $('#div1').click(function() { $('#div1 span:first').attr('class', 'newClassName'); }); +1
las
source share