jQuery 如何获取div的第一个span元素并更改类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10008433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:42:33  来源:igfitidea点击:

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

jquery

提问by user1184100

I have a div with a span

我有一个跨度的 div

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

When i click on div i want to change the class of only first span element of the div

当我单击 div 时,我只想更改 div 的第一个 span 元素的类

$('#div1').click(function() {
    // ... check if first span element inside the div .. if there and change the class..    
});  

回答by Andreas Wong

回答by Hemant Metalia

use

 $("div span:first-child")

as follow:

如下:

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

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

参考http://api.jquery.com/first-child-selector/

回答by Hiren H Patel

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

Like this you can get the value of span.

像这样你可以得到跨度的值。

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

您还可以使用 .html() 代替 .text() 方法。

回答by Kh?i

Multiple answers valid. My approach:

多个答案有效。我的做法:

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

回答by las

$('#div1').click(function() {    
   $('#div1 span:first').attr('class', 'newClassName');
});