javascript 如何获取跨度的类值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12665107/
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-10-26 16:48:58  来源:igfitidea点击:

how to get class value of a span

javascripthtml

提问by telexper

Possible Duplicate:
Get Class List for Element with jQuery

可能的重复:
使用 jQuery 获取元素的类列表

how can i get the class value of a span inside a div?

如何获取 div 中跨度的类值?

<div id="Check">

<span class="checked">

<input id="box" name="INbox" type="checkbox" value="1" />1<br>

<span>

</div>

how to get the value of class="checked" from on div="Check"?

如何从 div="Check" 上获取 class="checked" 的值?

and use it like this

并像这样使用它

<script>
var span = $('div#Outbound').find('span').attr('class');
if ( span != "checked"){

}
</script>

回答by Jo?o Silva

Use .attr():

使用.attr()

var spanClass = $('div#Outbound').find('span').attr('class');

Or if you just want to determine if the spanhas a class named checked, use .hasClass():

或者,如果您只想确定 是否span有名为 的类checked,请使用.hasClass()

var hasCheckedClass = $('div#Outbound').find('span').hasClass('class');

回答by Niet the Dark Absol

Without need for jQuery:

不需要 jQuery:

var span = document.getElementById('Check').getElementsByTagName('span')[0].className;

Or, if the format of the HTML is predictably "the span is the first element inside the div" then you can cheat a little:

或者,如果 HTML 的格式是可预见的“跨度是 div 中的第一个元素”,那么您可以作弊:

var span = document.getElementById('Check').children[0].className;

To check if the class checkedis on the span, you can do this:

要检查类checked是否在跨度上,您可以执行以下操作:

if( span.match(/\bchecked\b/))

回答by Anoop

You can use jQuery hasClass

你可以使用 jQuery hasClass

 <script>

    if ( !$('div#Outbound').find('span').hasClass( "checked" )){

    }
    </script>