views:

53

answers:

3

Dear all,

I have an element with a class. However, that element is not created when page is loaded, however it is created as a child-element as DOM ele. And each time if i want to check the availability of the class on this element it will return false eventho the class exists. I found out that it is because the element is not created when page loaded. May I know how to get is() and hasClass() to detect the class on DOM element? Thank you.

A: 

I'm not sure what your problem is. hasClass should give you the truth when the DOM is ready.

You can try something like this though:

function hasClass(el, className) {
  var elClass = " " + el.className + " ";
  return (elClass.indexOf( " " + className + " " ) !== -1);
}

note, it's more efficent than regex and only a little bit longer :)

galambalazs
I think you [meant to write](http://stackoverflow.com/questions/423823/whats-your-favorite-programmer-ignorance-pet-peeve/424005#424005) `return elClass.indexOf( " " + className + " " ) !== -1` as the last line of your function!
thenduks
yep. thx for pointing out.
galambalazs
A: 

This code works - alerts "true" twice. However if the elements you're looking for aren't visible at page load you'll need to bind your function to some other event. If you could provide your code it might help to figure out what the problem is.

<html>  
    <head>
        <script type="application/x-javascript" src="js/jquery-1.4.2.min.js" charset="utf-8"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $('#test').html('<span id="bluespan" class="blue">blue</span>');
            alert($('#bluespan').hasClass('blue'));
            alert($('span').is('#bluespan'));
        });
        </script>
    </head>
    <body>
        <div id="test">
        </div>
    </body>
</html>
dosboy
A: 

Thanks for all ur input. I found that it was my own mistake. It is now solved. Thank you.

limfreak