i have lots of divlayers with the class named ".current". depending on what the user does some of remove the class and some will get it again. this works fine, but what i want to is fire an event if only one div layer has the class ".current". how can i detect if only one element has the class current?
for example
if ($('#div4').hasClass('.current')) {
alert("fire me something");
}
something like "is the only one" hasClass.
in your event callback, simply check the number of divs that have the current class:
if ($('#div4').hasClass('current') && $('div.current').length === 1) {
...do stuff...
}
If you're only ever using current on divs, then you could just use $('.current').length === 1.
you should be able to use the css class as the selector and then get the length:
if($(".current").length == 1 ) {
alert('fire me something');
}
I "think" you could do:
if($('.current').length == 1) { //DO }
I believe the selector will return an array of the elements.
You have error syntaxe! you should add an ")" for your condition. and dont use the calss selecotr (".") . that's will work:
if($('#div4').hasClass('current')){
alert("fire me something");
}
You could see how many instances of the class .current that there are by using length. e.g.
var mycount = $(".current").length;
alert(mycount);
Then do whatever you like with the result.
See http://api.jquery.com/size/ or http://api.jquery.com/length/
$(".current").length
$(".current").size() *deprecated as of v1.8
Either will give you the count. Anytime you adjust the class check to see the count and fire the action if its 1
Related
Trying to perform action when <figure> with class .woocommerce-product-gallery__wrapper has another class alongside it - .test.
This .test class is placed there by another JavaScript powered button that's toggling the class in and out. So this event would need to continue listening.
if($( ".woocommerce-product-gallery__wrapper" ).hasClass( "test" )){
console.log('Hello');
// I have the 'hidden' class
};
I feel this is something super easy and as a JS noob, I'm doing something super stupid/missing something.
Try:
if(document.querySelector('.woocommerce-product-gallery__wrapper').classList.contains('test')){
console.log('Hello');
};
Consider the following.
if($(".woocommerce-product-gallery__wrapper.test" ).length > 0){
console.log('Found Test Element');
}
This will select all elements with both classes, woocommerce-product-gallery__wrapper and test.
You can also do something like.
$(".woocommerce-product-gallery__wrapper").each(function(i, el){
if($(el).hasClass("test")){
console.log("Found Test, Index: " + i);
}
});
This will iterate each element with class woocommerce-product-gallery__wrapper and check if it has the test class. This is helpful when you want to perform an action on just those elements.
You can also use .filter() like this.
$(".woocommerce-product-gallery__wrapper").filter(".test").css("background", "yellow");
There are lots of ways to find a specific element.
i need to remove some elements if no children...
this will work...
$$('*').each(function() {
($$(this).text().trim() === '') && $$(this).remove()
});
but it will look for all elements... i need to limit to some elements.. so i made this..
elements.forEach(element => {
$$(element).each(function() {
($$(this).text().trim() === '') && $$(this).remove()
});
})
but it doesn't work..
You can use :empty pseudo selector to collect all the empty elements:
$(':empty').remove(); // removes all the empty elements
If you target some specific elements then either give it a class name and use both in conjuction:
$('.theClass:empty').remove();
Or just use the tagnames of specific elements:
$('div:empty').remove(); // removes all the empty divs
You can use the id, classor tag in the jQuery selector. Try the following way:
$("div:empty").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div><span>test</span></div>
<div></div>
I like Mamun's approach. If you want to apply it on a certain collection of element types only you could modify/simplify it as such:
$("div,td,p,... and other elements").filter(":empty").remove();
Sorry, just noticed, that Jay also provided a part of my solution. I did not want to repeat things unecessarily here, but maybe the combination of the two is still relevant.
Remove all empty tags from current document
$("*:empty").remove();
If I understood correctly what you asked, you should rty :
if($("some selection").children() === undefined){
//do something
}
or as a function :
function rmIfNoChild(jQobj){
if(jQobj.children() === undefined){
//do something
}
}
How do I check if $(this) is a div, ul or blockquote?
For example:
if ($(this) is a div) {
alert('its a div!');
} else {
alert('its not a div! some other stuff');
}
Something like this:
if(this.tagName == 'DIV') {
alert("It's a div!");
} else {
alert("It's not a div! [some other stuff]");
}
Solutions without jQuery are already posted, so I'll post solution using jQuery
$(this).is("div,ul,blockquote")
Without jQuery you can say this.tagName === 'DIV'
Keep in mind that the 'N' in tagName is uppercase.
Or, with more tags:
/DIV|UL|BLOCKQUOTE/.test(this.tagName)
To check if this element is DIV
if (this instanceof HTMLDivElement) {
alert('this is a div');
}
Same for HTMLUListElement for UL,
HTMLQuoteElement for blockquote
if(this.tagName.toLowerCase() == "div"){
//it's a div
} else {
//it's not a div
}
edit: while I was writing, a lot of answers were given, sorry for doublure
Going through jQuery you can use $(this).is('div'):
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
Some of these solutions are going a bit overboard. All you need is tagName from regular old JavaScript. You don't really get any benefit from re-wrapping the whole thing in jQuery again, and especially running some of the more powerful functions in the library to check the tag name. If you want to test it on this page, here's an example.
$("body > *").each(function() {
if (this.tagName === "DIV") {
alert("Yeah, this is a div");
} else {
alert("Bummer, this isn't");
}
});
let myElement =document.getElementById("myElementId");
if(myElement.tagName =="DIV"){
alert("is a div");
}else{
alert("is not a div");
}
/*What ever you may need to know the type write it in capitalised letters "OPTIO" ,"PARAGRAPH", "SPAN" AND whatever */
I'm enhancing the answer of Andreq Frenkel, just wanted to add some and it became too lengthy so gone here...
Thinking about CustomElements extending the existing ones and still being able to check if an element is, say, input, makes me think that instanceof is the best solution for this problem.
One should be aware though, that instanceof uses referential equality, so HTMLDivElement of a parent window will not be the same as the one of its iframe (or shadow DOM's etc).
To handle that case, one should use checked element's own window's classes, something like:
element instanceof element.ownerDocument.defaultView.HTMLDivElement
Old question but since none of the answers mentions this, a modern alternative, without jquery, could be just using a CSS selector and Element.matches()
element.matches('div, ul, blockquote');
Try using tagName
first time posting here. I'm a beginner in jquery and i ran into some grey area. Hopefully i can find my answer here and learn from it also :)
So i have a let's say 10 different div. All has the same class. And everytime I click on the div it has to add another class (in this case background-color in css). For that I have this:
$(document).ready(function() {
$(".menucardmenu").click(function(){
if($(this).hasClass("menucardmenu")) {
$(this).addClass("backgroundmenucard");
}
else {
alert ("condition false");
}
});
});
But the question now is, how can i make that only one div can have that background-color (in my case backgroundmenucard). Depending one which div the user click, that div will have the background-color, and the previous div (that was clicked) should reset it back to normal. I can do it with this right?:
$(this).removeClass("backgroundmenucard");
does anyone know the answer to this???
Regards,
Andrew
try the following:
$(".menucardmenu").click(function(){
$(".backgroundmenucard").removeClass("backgroundmenucard");
$(this).addClass("backgroundmenucard");
});
Demo: http://jsfiddle.net/r2Sua/
(I remove the if because it's useless in this case)
Remove from all...
$(".menucardmenu").removeClass("backgroundmenucard");
Then add to this
$(function() // shorthand for document ready
{
var $divs = $('div.menucardmenu'), // standard jQuery "cache" idiom
BG_CLASS = 'backgroundmenucard'; // stay DRY, less prone to typos
$divs.live('click', function() // use .live to bind only 1 event listener
{
// remove the class from all divs
$divs.removeClass(BG_CLASS);
// add the class to this div
$(this).addClass(BG_CLASS);
}
});
});
The if($(this).hasClass("menucardmenu")) check is completely unnecessary since you're already selecting elements which have that class. It will always evaluate to true.
$('.menucardmenu').click(function(){
$('.menucardmenu').removeClass('backgroundmenucard');
$(this).addClass('backgroundmenucard');
});
Another option would be:
$(".menucardmenu").not(this).removeClass("backgroundmenucard");
$(this).addClass("backgroundmenucard");
This way you don't remove and add the class to the specific (this) element
I have a div:
<div class="test" id="someElement" style="position: absolute"></div>
Is there any way to check if the certain element:
$("#someElement")
has a particular class (in my case, "test").
Alternately, is there a way to check that en element has a certain style? In this example, I'd like to know if the element has "position: absolute".
Thank you very much!
CSS Styles are key-value pairs, not just "tags". By default, each element has a full set of CSS styles assigned to it, most of them is implicitly using the browser defaults and some of them is explicitly redefined in CSS stylesheets.
To get the value assigned to a particular CSS entry of an element and compare it:
if ($('#yourElement').css('position') == 'absolute')
{
// true
}
If you didn't redefine the style, you will get the browser default for that particular element.
if($('#someElement').hasClass('test')) {
... do something ...
}
else {
... do something else ...
}
if ($("element class or id name").css("property") == "value") {
your code....
}
Or, if you need to access the element that has that property and it does not use an id, you could go this route:
$("img").each(function () {
if ($(this).css("float") == "left") { $(this).addClass("left"); }
if ($(this).css("float") == "right") { $(this).addClass("right"); }
})
i've found one solution:
$("#someElement")[0].className.match("test")
but somehow i believe that there's a better way!
Question is asking for two different things:
An element has certain class
An element has certain style.
Second question has been already answered. For the first one, I would do it this way:
if($("#someElement").is(".test")){
// Has class test assigned, eventually combined with other classes
}
else{
// Does not have it
}