Determine if an element has a CSS class with jQuery - javascript

I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it.
I have the id of the element, and the CSS class that I'm looking for. I just need to be able to, in an if statement, do a comparison based on the existence of that class on the element.

Use the hasClass method:
jQueryCollection.hasClass(className);
or
$(selector).hasClass(className);
The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).
Note: If you pass a className argument that contains whitespace, it will be matched literally against the collection's elements' className string. So if, for instance, you have an element,
<span class="foo bar" />
then this will return true:
$('span').hasClass('foo bar')
and these will return false:
$('span').hasClass('bar foo')
$('span').hasClass('foo bar')

from the FAQ
elem = $("#elemid");
if (elem.is (".class")) {
// whatever
}
or:
elem = $("#elemid");
if (elem.hasClass ("class")) {
// whatever
}

As for the negation, if you want to know if an element hasn't a class you can simply do as Mark said.
if (!currentPage.parent().hasClass('home')) { do what you want }

Without jQuery:
var hasclass=!!(' '+elem.className+' ').indexOf(' check_class ')+1;
Or:
function hasClass(e,c){
return e&&(e instanceof HTMLElement)&&!!((' '+e.className+' ').indexOf(' '+c+' ')+1);
}
/*example of usage*/
var has_class_medium=hasClass(document.getElementsByTagName('input')[0],'medium');
This is WAY faster than jQuery!

In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:
element.classList.contains('your-class-name')

Check the official jQuery FAQ page :
How do I test whether an element has perticular class or not

$('.segment-name').click(function () {
if($(this).hasClass('segment-a')){
//class exist
}
});

In my case , I used the 'is' a jQuery function, I had a HTML element with different css classes added , I was looking for a specific class in the middle of these , so I used the "is" a good alternative to check a class dynamically added to an html element , which already has other css classes, it is another good alternative.
simple example :
<!--element html-->
<nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>
<!--jQuery "is"-->
$('#menu').is('.cbp-spmenu-open');
advanced example :
<!--element html-->
<nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>
<!--jQuery "is"-->
if($('#menu').is('.cbp-spmenu-bottom.cbp-spmenu-open')){
$("#menu").show();
}

Related

Check is style attribute does not exists using javascript selector method

I'm trying to only select ARTICLE items that do not have the style attribute set.
I could do this easily with jQuery but I'm using a library that is javascript only, called scrollreveal.
I can easy get items that have the style attribute using this ARTICLE[style].
But I want to reverse this and get items that do not have a style attribute, in the same way using a not equal to != operator on the selector.
I've tried this...
// scroll reveal article
window.sr = new ScrollReveal({ reset: false });
sr.reveal('ARTICLE[!=style]', {
duration: 1000
});
But it's not working as expected, does anyone know if its possible to achieve this using not equal too on a attribute selector?
Thanks in advance for any help on this.
Almost there. The :not pseudoclass should do the trick:
article:not([style])
Just use :not([style]):
const matches = document.querySelectorAll('div:not([style])')
console.log(matches)
<div id="foo" style="width:100px;"></div>
<div id="bar"></div>
<div id="baz"></div>
That is if I'm correct in assuming that sr.reveal uses document.querySelector internally.

select html object without id

Edit: one missing piece of information - I can't use the class selector because there are more divs with the same class. I already thought of that, but I forgot to mention it. I have no idea why my post got downvoted, but it seems awfully silly considering I provided a lot of information, gave it honest effort, and tried to be verbose with code examples. People on this forum are ridiculous sometimes.
I'm trying to set the id of a div that doesn't have one and there's no way I can give it one upon generation of the page. I've tried using jquery (.each, .contains, .find, .filter, etc.) and I can't seem to get it right. I know a ton of people have asked this question, but none of the answers made sense to me.
I have the ability to set the text (html?) of the div, but nothing else. It ends up looking like this:
<div class="dhxform_note" style="width: 300px;">Remaining letters: 500</div>
I want a handle to the div object so I can show the user how many more letters they can type by updating the text.
Using this:
$("div")
returns a list of all divs on the page. I can see the target div in the list, but I can't get jquery to return a single object.
I know it can also be done with something like this:
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++) {
if( /^Remaining letters/.test(divs[i].innerText) )
divs[i].id = "kudosMsgNote"
}
}
but I was hoping to complete this with a cleaner looking solution involving jquery. I also simply want to know how to do it with jquery, aesthetics not withstanding.
Use a class selector.
var theDivViaTheClass = $(".dhxform_note");
Class Selector (“.class”)
Description: Selects all elements with the given class.
version added: 1.0
jQuery( ".class" )
class: A class to search for. An
element can have multiple classes; only one of them must match.
For class selectors, jQuery uses JavaScript's native
getElementsByClassName() function if the browser supports it.
You seem to be targeting the <div> by its text. Try using the :contains selector:
$("div").filter(':contains("Remaining letters")').first().attr("id", "kudosMsgNote");
The .first() is to make sure you don't set the same id for multiple elements, in case multiple elements contain the text "Remaining letters".
Here's the docs for the :contains selector: http://api.jquery.com/contains-selector/
Be careful, the text you're looking for is case sensitive when using :contains!
Is that div the only one with the class dhxform_note? If so, you can use the class selector:
$('.dhxform_note').html();
With jQuery, you can specify any css selector to get at the div:
$(".dhxform_note").attr("id", "kudosMsgNote");
will get you this element as well.
Selecting on inner text can be a bit dicey, so I might recommend that if you have control over the rendering of that HTML element, you instead render it like this:
<div name="remainingLetters" class="dhxform_note" style="width: 300px">Remaining Letters: 500</div>
And get it like this:
$("[name=remainingLetters]").attr("id", "kudosMsgNote");
However, it's possible that you really need to select this based on the inner text. In that case, you'll need to do the following:
$("div").each(function() {
if ( /^Remaining letters/.test($(this).html()) ) {
$(this).attr("id", "kudosMsgNote");
}
});
If you cannot set id for whatever reason, I will assume you cannot set class either. Maybe you also don't have the exclusive list of classes there could be. If all those assumptions really apply, then you can consider down your path, otherwise please use class selector.
With that said:
$("div").filter(function() {
return /^Remaining letters/.test($(this).text())
}).attr('id', 'id of your choice');
For situations where there are multiple divs with the class dhxform_note and where you do not know the exact location of said div:
$("div.dhxform_note").each(function(){
var text = $(this).text();
if(/^Remaining letters/.test(text)){
$(this).attr("id", "kudosMsgNote");
}
});
EXAMPLE
If, however, you know that the div will always be the 2nd occurrence of dhxform_note then you can do the following:
$("div.dhxform_note").get(1).id = "kudosMsgNote";
EXAMPLE
Or do a contains search:
$("div.dhxform_note:contains('Remaining letters')").first().attr("id", "kudosMsgNote");
EXAMPLE

How to use in jQuery :not and hasClass() to get a specific element without a class

I have this line of code:
$('#sitesAccordion .groupOfSites').click(function() {
var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
console.log(lastOpenSite);
});
I get "false" instead of getting one of the other elements (assuming that there is one - and there must be). I guess the problem is with:
.hasClass(':not(.closedTab)');
What is the problem?
My purpose is to create my own accordion (without using jQuery UI)
and I am trying to write it like this:
$('#sitesAccordion .groupOfSites').click(function() {
//Get the last opened tab
var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
//Close last opened tab and add class
lastOpenSite.hide().toggleClass('closedTab');
//Open the current Tab
$(this).children('.accordionContent').toggle('fast');
// remove class from open tab
$(this).toggleClass('closedTab');
});
Is this the best way?
thanks,
Alon
Use the not function instead:
var lastOpenSite = $(this).siblings().not('.closedTab');
hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.
It's much easier to do like this:
if(!$('#foo').hasClass('bar')) {
...
}
The ! in front of the criteria means false, works in most programming languages.
jQuery's hasClass() method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.
For ex: x.hasClass('error');
You can also use jQuery - is(selector) Method:
var lastOpenSite = $(this).siblings().is(':not(.closedTab)');
I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.
$(this).siblings(':not(.closedTab)');

Get class name using jQuery

I want to get the class name using jQuery
And if it has an id
<div class="myclass"></div>
After getting the element as jQuery object via other means than its class, then
var className = $('#sidebar div:eq(14)').attr('class');
should do the trick. For the ID use .attr('id').
If you are inside an event handler or other jQuery method, where the element is the pure DOM node without wrapper, you can use:
this.className // for classes, and
this.id // for IDs
Both are standard DOM methods and well supported in all browsers.
It is better to use .hasClass() when you want to check if an element has a particular class. This is because when an element has multiple class it is not trivial to check.
Example:
<div id='test' class='main divhover'></div>
Where:
$('#test').attr('class'); // returns `main divhover`.
With .hasClass() we can test if the div has the class divhover.
$('#test').hasClass('divhover'); // returns true
$('#test').hasClass('main'); // returns true
Be Careful , Perhaps , you have a class and a subclass .
<div id='id' class='myclass mysubclass' >dfdfdfsdfds</div>
If you use previous solutions , you will have :
myclass mysubclass
So if you want to have the class selector, do the following :
var className = '.'+$('#id').attr('class').split(' ').join('.')
and you will have
.myclass.mysubclass
Now if you want to select all elements that have the same class such as div above :
var brothers=$('.'+$('#id').attr('class').split(' ').join('.'))
that means
var brothers=$('.myclass.mysubclass')
Update 2018
OR can be implemented with vanilla javascript in 2 lines:
const { classList } = document.querySelector('#id');
document.querySelectorAll(`.${Array.from(classList).join('.')}`);
This is to get the second class into multiple classes using into a element
var class_name = $('#videobuttonChange').attr('class').split(' ')[1];
you can simply use,
var className = $('#id').attr('class');
If your <div> has an id:
​<div id="test" class="my-custom-class"></div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
...you can try:
var yourClass = $("#test").prop("class");
If your <div> has only a class, you can try:
var yourClass = $(".my-custom-class").prop("class");
If you're going to use the split function to extract the class names, then you're going to have to compensate for potential formatting variations that could produce unexpected results. For example:
" myclass1 myclass2 ".split(' ').join(".")
produces
".myclass1..myclass2."
I think you're better off using a regular expression to match on set of allowable characters for class names. For example:
" myclass1 myclass2 ".match(/[\d\w-_]+/g);
produces
["myclass1", "myclass2"]
The regular expression is probably not complete, but hopefully you understand my point. This approach mitigates the possibility of poor formatting.
To complete Whitestock answer (which is the best I found) I did :
className = $(this).attr('class').match(/[\d\w-_]+/g);
className = '.' + className.join(' .');
So for " myclass1 myclass2 " the result will be '.myclass1 .myclass2'
<div id="elem" class="className"></div>
With Javascript
document.getElementById('elem').className;
With jQuery
$('#elem').attr('class');
OR
$('#elem').get(0).className;
You can get class Name by two ways :
var className = $('.myclass').attr('class');
OR
var className = $('.myclass').prop('class');
If you do not know the class name BUT you know the ID you can try this:
<div id="currentST" class="myclass"></div>
Then Call it using :
alert($('#currentST').attr('class'));
If you want to get classes of div and then want to check if any class exists then simple use.
if ( $('#div-id' ).hasClass( 'classname' ) ) {
// do something...
}
e.g;
if ( $('body').hasClass( 'home' ) ) {
$('#menu-item-4').addClass('active');
}
Try it
HTML
<div class="class_area-1">
area 1
</div>
<div class="class_area-2">
area 2
</div>
<div class="class_area-3">
area 3
</div>
jQuery
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="application/javascript">
$('div').click(function(){
alert($(this).attr('class'));
});
</script>
If we have a code:
<div id="myDiv" class="myClass myClass2"></div>
to take class name by using jQuery we could define and use a simple plugin method:
$.fn.class = function(){
return Array.prototype.slice.call( $(this)[0].classList );
}
or
$.fn.class = function(){
return $(this).prop('class');
}
The use of the method will be:
$('#myDiv').class();
We have to notice that it will return a list of classes unlike of native method element.className which returns only first class of the attached classes. Because often the element has more than one class attached to it, I recommend you not to use this native method but element.classlist or the method described above.
The first variant of it will return a list of classes as an array, the second as a string - class names separated by spaces:
// [myClass, myClass2]
// "myClass myClass2"
Another important notice is that both methods as well as jQuery method
$('div').prop('class');
return only class list of the first element caught by the jQuery object if we use a more common selector which points many other elements. In such a case we have to mark the element, we want to get his classes, by using some index, e.g.
$('div:eq(2)').prop('class');
It depends also what you need to do with these classes. If you want just to check for a class into the class list of the element with this id you should just use method "hasClass":
if($('#myDiv').hasClass('myClass')){
// do something
}
as mentioned in the comments above. But if you could need to take all classes as a selector, then use this code:
$.fn.classes = function(){
var o = $(this);
return o.prop('class')? [''].concat( o.prop('class').split(' ') ).join('.') : '';
}
var mySelector = $('#myDiv').classes();
The result will be:
// .myClass.myClass2
and you could get it to create dynamically a specific rewriting css rule for example.
Regards
This works too.
const $el = $(".myclass");
const className = $el[0].className;
if we have single or we want first div element we can use
$('div')[0].className otherwise we need an id of that element
Best way to get class name in javascript or jquery
attr() attribute function is used to get and set attribute.
Get Class
jQuery('your selector').attr('class'); // Return class
Check class exist or not
The hasClass() method checks if any of the selected elements have a specified class name.
if(jQuery('selector').hasClass('abc-class')){
// Yes Exist
}else{
// NOt exists
}
Set Class
jQuery('your selector').attr('class','myclass'); // It will add class to your selector
Get Class on Click of button using jQuery
jQuery(document).on('click','button',function(){
var myclass = jQuery('#selector').attr('class');
});
Add class if selector have no any class using jQuery
if ( $('#div-id' ).hasClass( 'classname' ) ) {
// Add your code
}
Get the second class into multiple classes using into a element
Change array position in place of [1] to get particular class.
var mysecondclass = $('#mydiv').attr('class').split(' ')[1];
Direct way
myid.className
console.log( myid.className )
<div id="myid" class="myclass"></div>
use like this:-
$(".myclass").css("color","red");
if you've used this class more than once then use each operator
$(".myclass").each(function (index, value) {
//do you code
}

How to change a css class style through Javascript?

According to the book I am reading it is better to change CSS by class when you are using Javascript. But how? Can someone give a sample snippet for this?
Suppose you have:
<div id="mydiv" class="oldclass">text</div>
and the following styles:
.oldclass { color: blue }
.newclass { background-color: yellow }
You can change the class on mydiv in javascript like this:
document.getElementById('mydiv').className = 'newclass';
After the DOM manipulation you will be left with:
<div id="mydiv" class="newclass">text</div>
If you want to add a new css class without removing the old one, you can append to it:
document.getElementById('mydiv').className += ' newClass';
This will result in:
<div id="mydiv" class="oldclass newclass">text</div>
Since classList is supported in all major browsers and jQuery drops support for IE<9 (in 2.x branch as Stormblack points in the comment), considering this HTML
<div id="mydiv" class="oldclass">text</div>
you can comfortably use this syntax:
document.getElementById('mydiv').classList.add("newClass");
This will also result in:
<div id="mydiv" class="oldclass newclass">text</div>
plus you can also use remove, toggle, contains methods.
If you want to manipulate the actual CSS class instead of modifying the DOM elements or using modifier CSS classes, see
https://stackoverflow.com/a/50036923/482916.
I'd highly recommend jQuery. It then becomes as simple as:
$('#mydiv').addClass('newclass');
You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();
The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.
$('div').addClass('newclass');
$('.oldclass').addClass('newclass');
The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.
use the className property:
document.getElementById('your_element_s_id').className = 'cssClass';
There are two ways in which this can be accomplished using vanilla javascript. The first is className and the second is classList. className works in all browsers but can be unwieldy to work with when modifying an element's class attribute. classList is an easier way to modify an element's class(es).
To outright set an element's class attribute, className is the way to go, otherwise to modify an element's class(es), it's easier to use classList.
Initial Html
<div id="ID"></div>
Setting the class attribute
var div = document.getElementById('ID');
div.className = "foo bar car";
Result:
<div id="ID" class="foo bar car"></div>
Adding a class
div.classList.add("car");// Class already exists, nothing happens
div.classList.add("tar");
Note: There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.
Result:
<div id="ID" class="foo bar car tar"></div>
Removing a class
div.classList.remove("car");
div.classList.remove("tar");
div.classList.remove("car");// No class of this name exists, nothing happens
Note: Just like add, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.
Result:
<div id="ID" class="foo bar"></div>
Checking if a class attribute contains a specific class
if (div.classList.contains("foo")) {
// Do stuff
}
Toggling a class
var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed
classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added
.toggle has a second boolean parameter that, in my opinion, is redundant and isn't worth going over.
For more information on classList, check out MDN. It also covers browser compatibility if that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.
document.getElementById("my").className = 'myclass';
You may also be interested in modifying it using jQuery:
http://api.jquery.com/category/css/
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").addClass(function(){
return "par" ;
});
});
</script>
<style>
.par {
color: blue;
}
</style>
</head>
<body>
<div class="test">This is a paragraph.</div>
</body>
</html>

Categories

Resources