开发者

Help needed in using hasClass() to check <div> class in document

I a trying 开发者_JAVA技巧to check for DIV class in my document.

But it is not working for me,Please help me.. Below is my code

$(document).ready(function()
{
var x=$(this).hasClass('global');
alert(x);
});

And even i have tried below code but still same result..

  $(document).ready(function()
  {
   var x=$('#global').length;
   alert(x);
  });

It is always showing 0..... :-(


It's hard to tell exactly what you want to do but i'll assume you want to know if there is an item in the DOM with the class you specify.

It'd be simpler if you did:

var x = $(".global");

alert(x.size());


this is referring to the document you need to refer to a div element

$('div').hasClass('global')

or even simpler:

$('div.global')

you can then iterate through all of the divs found using the this keyword and the each function

$('div.global').each(function(){
    console.log($(this)); // trace out each element found 
});


You're checking if the document has a class of 'global'. What you want is:

$(document).ready(function() {
   var x=$("div.global");
   alert("There is "+x.size()+" divs with class 'global'");
});

but if you want to get them all and do something use EACH:

$(document).ready(function() {
    $("div.global").each(function() {
       //do something here
       alert("I have the class global");
    });
});


You need to select your div, not this, to determine if it has the class in question:

<div id="myDiv" class="global"></div>

$('#myDiv').hasClass('global');


$(this) in the $(document).ready() refers to the window object (do an alert($(this).get(0)) to see what I mean).

If you want the amount of of divs with the global class you should do:

alert($('div.global').length);


$(function()
{
  var x = $("div.global");
  alert(x);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜