Reputation: 83
<div class="Trade">
<div id="Offer">
<div class="NoResults">No Result!</div>
<div class="FooterPager"> <span id="Offer"><a disabled="disabled">First</a> <a disabled="disabled">Previous</a> <a disabled="disabled">Next</a> <a disabled="disabled">Last</a> </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.
Upvotes: 8
Views: 40562
Reputation: 13
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'))
Upvotes: 0
Reputation: 4278
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.
Upvotes: 1
Reputation: 219920
if ( ~(' ' + element.className + ' ').indexOf(' NoResult ') ) {
// here you go. You've got that class...
}
Upvotes: 1
Reputation: 490153
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;
Upvotes: 22