If element has "class1" and/or "class2" in Jquery .hasClass() function - javascript

I want to check if an element has this class or another class like this:
if ( $elem.hasClass("foo") || $elem.hasClass("bar") ) {
// do something
}
And I also want to check if an element has two classes:
if ( $elem.hasClass("foo") && $elem.hasClass("bar") ) {
// do something else
}
Is there a way to do this all within the hasClass() function? Something like:
if ( $elem.hasClass("foo bar") ) {
// do something when element has both classes
}
else if ( $elem.hasClass("foo","bar") ) {
// do something when element has either class
}

Strictly answering to your question: no, you can not.
hasClass() accepts a single argument.
As pointed out by others, you might use is(), but here is a test that shows that performances are very much penalized.
I suggest you to stay with your current code.

You could do something a little different to accomplish this. Not sure if this meets your needs though.
Use multiple selectors you can see if an element that matches exists on the page
Use each to execute the code you want
Example of something like this:
$("span.foo, span.bar").each( function() {
$(".test").html("foo or bar was found");
});
JS Fiddle: http://jsfiddle.net/s3gL5pwm/1/
A second solution that uses if would be to use .is() instead.
For example:
if ($("span").is(".foo, .bar")) {
$(".test").html("foo or bar exists");
};
JSfiddle: http://jsfiddle.net/eL2a8smt/

Related

How do I check if an element is NOT empty with jquery?

I need to check if an element is empty and if another is NOT empty. The first part of the if works but how do I check if the #dynamicForm element is NOT empty?ยจ
This obviously doesn't work but I need something like it:
if ($("#formButton").is(':empty') && $("#dynamicForm").is(':notempty')) {
//do stuff
}
if(!$("#dynamicForm").is(':empty')){
// code here...
}
Note the not operator (!) in front.
First of all you can check if the selected element is empty and negate it:
!$('#dynamicForm').is(':empty')
Furthermore you can check if it's not empty with jquery selector :not:
$('#dynamicForm').is(':not(:empty)')
A third way would be to select all elements, that are not empty and check the length of the jquery collection:
$('#dynamicForm').not(':empty').length
If you need this check in several places you can add your own function to jQuery:
$.fn.notEmpty = function() {
return !$(this).is(':empty')
}
you can use it like this:
if($('#dynamicForm').notEmpty())
That isn't realy clean and it's not keeping with the jquery conventions. So better extend the selectors instead of extending the functions:
$.extend($.expr[':'],{
notEmpty:function(c) {
return !$(c).is(':empty');
}
});
Now you can use it very straightforward:
if($('#dynamicForm').is(':notEmpty'))

Remove element depending on it's background-image

I'm trying to remove an element from a page based on it's background attribute.
Something like:
if ( $('td').attr('background','backgroundimageurl')){this.remove();}
But this does not work any suggestions?
You can also use filter to filter the result set based on your operations:
$( 'td' ).filter( function(){
// return true of it matches, thus, keeping it in the object
return $(this).css( 'backgroundImage' ) === 'someUrlOrWhatever';
}).remove();
Demo per roXon's request: http://jsfiddle.net/danheberden/9rTZj/
However, it would be better to do a check like
return /someDomain\.com\/path\/to\/whatever/.test( $( this ).css( 'backgroundImage' ) );
in the filter function. Different browsers will return different formatting for css rules, as roXon pointed out about the === approach won't work in FF because the returned string will be url("thePath") instead of url(thePath) like in webkit. Thus, just testing for the url value would be most flexible.
The reason it's not working is that in your code snippet, "this" is the current context (most likely the window).
This might do what you want:
$('td').each(function (i, e) {
if (e.style.foo === "bar") {
$(e).remove();
}
});
each iterates through all of the elements that matched. i is the number of the loop, and e is the current element. So we test each element and then act when we find the one with the style we want.
Even shorter example:
$('td[background="backgroundimageurl"]').remove();
Do some reading on jQuery selectors. They can be really useful :)
http://api.jquery.com/category/selectors/
Try this. When you were doing attr("background","backgroundurl") this was trying to set the background attr rather than find elements matching. This will do the trick.
if($("body").find("td").css("background-image") == "backgroundimageurl"){this.detach()};

JavaScript/jQuery "if" condition syntax

I'm attempting to evaluate a class to see if it contains some text in my click handler, but I can't get my code to act properly. What am I missing?
The if statement is looking to see whether the class of the clicked object has the word "headline" in it.
$('[class^=edit_]').click(function(){
var element = $(this).attr('class');
var field = element.split(/_(.+)/)[1];
if ($(this).attr('[class*=headline]'))
{
alert("headline");
}
else
{
alert("not headline");
};
});
Is it possible to construct my if statement with something that evaluates the var field = element.split(/_(.+)/)[1]; since that is really where the information resides.
Something like:
if (element *= "headline"){do this};
I'm not sure I understand all of the "evaluators" that exist in JavaScript to know if I can evaluate a string like that.
Upon re-reading your question, there's an even simpler approach, just check the .className for the string you want using .indexOf(), like this:
if (this.className.indexOf('headline') != -1)
Previous answer:
The closest version to what you have, checking if an element matching a selector is .is(), like this:
if ($(this).is('[class*=headline]'))
But there's another method more appropriate here (if you're checking for a full class, not part of one), you can use .hasClass() like this:
if ($(this).hasClass('headline'))

How do I use hasClass to detect if a class is NOT the class I want?

How do I use hasClass so it works as doesNotHaveClass? In other words, rather than looking to see if it is a specified class, looking to see if it is NOT a specified class. Can I use an exclamation point or something like that?
Yes, you can.
if (!$('element').hasClass('do-not-want')) {
// This element does not have the .do-not-want class
}
However if you're trying to use selectors to find all the items that don't have a class, perhaps try this:
// find all divs that don't have "badClass" class
$('div').not('.badClass').each(function(){});
if (!$('a').hasClass('xyz')){
...
}
Yes, you can
As per the jQuery documentation:
The .hasClass() method will return true if the class is assigned to an element, even if other classes also are.
Since the function returns a boolean you can use exclamation point to negate the result.
You can check if the return is false:
if($(element).hasClass("class") === false) {...}

How can I tell whether an element matches a selector?

Let's say I've got a DOM element - how can I tell whether it matches a jQuery selector, such as p or .myclass? It's easy to use the selector to match children of the element, but I want a true/false answer to whether this particular element match?
The element may not have an ID (and I can't assign it a random one for reasons beyond this), so I can't apply my selector to the element's parent and look for children with the same ID as mine.
Will this work as intended? I can't figure out Javascript object comparisons.
$(selector, myElement.parentNode).each({
if (this == myElement) // Found it
});
Seems like there would be an easy way to see whether a DOM element matches a jQuery selector...
You can use the is() method:
if($(this).is("p")){
// ...
}
Without jQuery, using Element.matches():
var elements = document.querySelectorAll('div');
console.log(
elements[0].matches('.foo'), // true
elements[0].matches('.bar'), // false
elements[1].matches('[title=bar]'), // true
)
<div class='foo'></div>
<div title='bar'></div>
See supported browsers list
I believe the is() method is what you are looking for.
Otherwise, you might just try selecting the item directly, if that is what you mean.
So if it's an "a" with a class of "myclass", just do $("a.myclass")
I can't apply my selector to the
element's parent and look for children
with the same ID as mine.
You can't do that anyway - the id attribute must be unique.
Maybe you just want:
$(".complicated #selector p.with > div.manyParts").length
If there are no matches, length returns 0, which is falsy, so you can use it in an if statement, like:
if($(".doesThis #exist").length) {
// Do things
}
Probably would be worth storing it in a separate variable and THEN checking the length; that way, if you need to do anything with the matched elements, you don't have to execute the same selector again.
Try Element.matches()
Element.matches()
document.addEventListener("click", event => {
if (event.target.matches(".elementsClass")) {
// It matches
} else {
// Does not match
}
});

Categories