简体   繁体   中英

Javascript: Check if classname exists

<div class="Trade">
    <div id="Offer">
        <div class="NoResults">No Result!</div>
        <div class="FooterPager"> <span id="Offer"><a disabled="disabled">First</a>&nbsp;<a disabled="disabled">Previous</a>&nbsp;<a disabled="disabled">Next</a>&nbsp;<a disabled="disabled">Last</a>&nbsp;</span>
        </div>
    </div>
</div>

Here is my javascript:

function Check(){
return !(iframe.contentDocument.getElementById("Offer").firstElementChild.tagName.toLowerCase() == "table");
}

Is it possible to return a true or false value to check if the class "NoResult" exists? If so, how do I do it? You guys rocks. I can't change the HTML coding, only the javascript.

Use classList .

var hasClass = element.classList.contains('some-class');

Further Reading (disclaimer: link to my own post).

If not supported in your target platforms, then try...

var hasClass = (" " + element.className + " ").indexOf(" some-class ") > -1;

In Javascript without using a library like jQuery, you could do it by:

(' ' + MyElement.className + ' ').indexOf(' MyClassName ') != -1

This evaluates to true when "MyClassName" appears anywhere by itself inside the string as defined on the className property.

In your specific case, something like:

function Check()
{
    //Returns true when it exists
    return (' ' + iframe.contentDocument.getElementById('Offer').firstElementChild.className + ' ').indexOf(' NoResults ') != -1;
}

There was previously a mistake in my answer where it would incorrectly identify a partial match as pointed out in the comments. Basically, you need to consider in the check that the class name is whole. A neat way to do this (like the other answers show) is that if you spaces before and after both the entire className property and the class you are searching for, it will always find the whole class.

While this will work, I recommend Alex's answer as while classList isn't available in every browser (<= IE9 and a few others), it is a neater solution to the problem.

if ( ~(' ' + element.className + ' ').indexOf(' NoResult ') ) {
    // here you go. You've got that class...
}

How to check if an element has a class for all browsers: JQuery 1.6 or lower

    if($("#ElementId").attr('class').indexOf('ClassName') > -1)

JQuery 1.6 or higher

    if($("#ElementId").prop('class').indexOf('ClassName') > -1)

Or, if you are not going to use IE at all

    if($("#ElementId").prop('class').includes('ClassName'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM