开发者

Get the class of the first DIV from inside HTML

开发者 https://www.devze.com 2023-03-27 13:50 出处:网络
<div class=\"first\"> <div class=\"second\"> etc </dv> </div> How can I get the class of the first div ? (\"first\") using jQuery ?
<div class="first">
 <div class="second">

   etc
 </dv>
</div>

How can I get the class of the first div ? ("first") using jQuery ?

I have this html inside a v开发者_运维技巧ariable "$body_html"


$("div:first").attr("class")

That'll do it for you.


You can achieve it eg. like that:

var element = jQuery('div:first');
alert(element.attr('class'));

See this jsfiddle for a proof.


var classString=$("div:first").attr("class")
var classArray= classString.split(" ");

Since Element you are looking for may have multiple css-classes, with above code you can get an array of css-classes an element is having.

If you just want to check whether an element is having particular class do as below

var boolResult= $("div:first").hasClass('classToTest');


$($body_html + ' div:first').attr('class');

This finds the first div within the variable with your html markup and gets its class attribute.

Here's a jsfiddle: http://jsfiddle.net/YSdCX/1/


 var thisClass = $("div:first").attr("class");

Will get the class attribute of the first <div> using the :first selector. See here for its use.

Alternatively you may be best selecting the <div> by id if your markup does change.

Also attr(attribute) can be used to get any attribute present on an element so can be useful for getting id attributes and so on.


Leah. Unfortunately, I don't know in what way exactly you are going to get this class. But I suppose, that the next ideas can help you. If you know the second class you may use the next code

    $('.second').closest('div').attr('class');

If you don't, you may add the id to the first div tag and then use

    $('#divid').attr('class')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号