Jquery: How to check if the element has certain css class/style - javascript

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
}

Related

remove some elements if no children

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
}
}

event if only one div has class

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

Check if element is a div

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

jquery visibility selector

I'd like to know if there's anything incorrect in the following :
if($('#three').is(':visible')) {
alert("visible");
} else {
alert("hidden");
}
Thanks
Your code seems correct to me. However, visible selector on jQuery defines a not visible elements if:
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
Is it the case in your test?
Some others importants aspect regarding this selector is that elements with visibility: hidden or opacity: 0 are considered to be visible!
Also, since 1.3.2, this selector has evolved, as stated in the changelog.
Better you check this : :visible Selector
<script>
if( $('#foo').is(':visible') ) {
// it's visible, do something
}
else {
// it's not visible so do something else
}
if( $('#foo').is(':hidden') ) {
// it's hidden, do something
}
else {
// it's not hidden so do something else
}
</script>
Make sure that #three has display attribute set to some default value. E.g. Display="none"

Select all elements that have a specific CSS, using jQuery

How can I select all elements that have a specific CSS property applied, using jQuery? For example:
.Title
{
color:red;
rounded:true;
}
.Caption
{
color:black;
rounded:true;
}
How to select by property named "rounded"?
CSS class name is very flexible.
$(".Title").corner();
$(".Caption").corner();
How to replace this two operation to one operation. Maybe something like this:
$(".*->rounded").corner();
Is there any better way to do this?
This is a two year old thread, but it was still useful to me so it could be useful to others, perhaps. Here's what I ended up doing:
var x = $('.myselector').filter(function () {
return this.style.some_prop == 'whatever'
});
not as succinct as I would like, but I have never needed something like this except now, and it's not very efficient for general use anyway, as I see it.
Thank you, Bijou. I used your solution, but used the jQuery .css instead of pure javascript, like this:
var x = $('*').filter(function() {
return $(this).css('font-family').toLowerCase().indexOf('futura') > -1
})
This example would select all elements where the font-family attribute value contains "Futura".
You cannot (using a CSS selector) select elements based on the CSS properties that have been applied to them.
If you want to do this manually, you could select every element in the document, loop over them, and check the computed value of the property you are interested in (this would probably only work with real CSS properties though, not made up ones such as rounded). It would also would be slow.
Update in response to edits — group selectors:
$(".Title, .Caption").corner();
Similar as Bijou's. Just a little bit enhancement:
$('[class]').filter(function() {
return $(this).css('your css property') == 'the expected value';
}
).corner();
I think using $('[class]') is better:
no need to hard code the selector(s)
won't check all HTML elements one by one.
Here is an example.
Here is a clean, easy to understand solution:
// find elements with jQuery with a specific CSS, then execute an action
$('.dom-class').each(function(index, el) {
if ($(this).css('property') == 'value') {
$(this).doThingsHere();
}
});
This solution is different because it does not use corner, filter or return. It is intentionally made for a wider audience of users.
Things to replace:
Replace ".dom-class" with your selector.
Replace CSS property and value with what you are looking for.
Replace "doThingsHere()" with what you want to execute on that
found element.
Good luck!
Custom CSS properties aren't inherited, so must be applied directly to each element (even if you use js to dynamically add properties, you should do it by adding a class), so...
CSS
.Title
{
color:red;
}
.Caption
{
color:black;
}
HTML
You don't need to define a rounded:true property at all. Just use the presence of the 'Rounded' class:
<div class='Title Rounded'><h1>Title</h1></div>
<div class='Caption Rounded'>Caption</div>
JS
jQuery( '.Rounded' ).corner();

Categories

Resources