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
}
Related
Is there a methodToCreate in jQuery which could be written as
$("#someId").methodToCreate("tagName", ".className");
where an element with tag tagName would be added and given a class className and that too inside a specific element which would have an id someId?
$("<tag></tag>").addClass("className").attr({id: 'someId'}).appendTo( "body" )
Here's and example setting all the attributes individually.
As pointed out such function doesn't exist, but you could always create one .
(function( $ ){
$.fn.methodToCreate= function(tagName,className,id) {
$(id).append("<"+tagName+" "+"class="+"\'"+className+"\'>"+"SampleContent"+"</"+tagName+">");
return this;
};
})( jQuery );
and you can call this whenever you want in the following manner :
$(document).ready(function(){
$(document).methodToCreate('p','sampleClass','#someId');
});
Using this function(methodToCreate) you can dynamically pass the tagName , className and id of the element that you want to append to.
Here is the working fiddle : https://jsfiddle.net/varunsinghal65/udrxeg9m/1/#&togetherjs=TBEnLAnNzJ
Using jQuery you can create an element
var el = $('<tagName class="className"/>');
and then add it to a container
$('#someId').append(el);
$('#someId').append('<tagname class="className"></tagname>');
if you have the class stored in a variable (for example myClass) don't forget to quote it like this:
$('#someId').append('<tagname class="' + myClass + '"></tagname>');
No that method does not exist, but you can use .appendTo
like:
$("<tagName class='className'></tagName>").appendTo("#someId");
Hope it helps.
I have dynamically generated div that receives two generated classes applied to it. For example, I have :
<div class="container">...</div>
Then after I mess with it using some Javascript, it becomes:
<div class="container post post-hello-world">...</div>
For this example how can I grab the third class (post-hello-world) and store it somewhere to be used for something else in my Javascript code using pure Javascript?
Use classList and item if the class you want is always third:
var className = document.getElementsByClassName('container')[0].classList.item(2);
See
MDN: Element.classList
Demo
Try before buy
You can do something like this:
var element = document.querySelector(".container");
var thirdClass = element.classList[2];
You may also what to use some checks to make sure that the element has 3 or more classes. Something like if(element.classList.length >= 3)
HTML:
I've attached a simplified example of the problem I'm facing:
<h2>Product2</h2>
<div id="products">
<a class="my-product1" href="#"><span>my-product1<span></a>
<a class="my-product2" href="#"><span>my-product2<span></a>
<a class="my-product3" href="#"><span>my-product3<span></a>
<a class="my-product4" href="#"><span>my-product4<span></a>
<a class="my-product5" href="#"><span>my-product5<span></a>
</div>
Javascript:
I'm already pulling myProduct from the page title and forcing lowercase. Next I'm attempting to remove this product from the group of links based on its class. Its quite possible this is jquery101 however I can't figure out how to add a class to a link using a variable to determine which class to select. In this example lets assume var myProduct = Product2
function removeProduct(myProduct){
$("a.myProduct").addClass("display-none");
};
Also, I am still learning so if you have the time a Brief explination of why what i'm doing is wrong would go a long way. Thanks for your time!
Simply concat the class name to the selector string:
$("a."+variable)...
Extra info as you requested:
Don't use a class "display-none"... change it's name or use jQuery native code that hides elements(hide(docs))
function removeProduct(myProduct){
$("a." + myProduct).hide();
};
Changing css rules is with the css(docs) function:
function removeProduct(myProduct){
$("a." + myProduct).css('display', 'none');
};
Adding class is with addClass function:
function removeProduct(myProduct){
$("a." + myProduct).addClass('someClass');
};
Change myProduct and removeProduct names to more meaningful variable names:
function hideAnchorElement(className){
$("a." + className).hide();
}
The class attribute / property is used as a generic selector - ie you can apply a class to multiple objects ... the id attribute / property is used for specific selection - and are unique. I suggest you change your HTML to use ids instead of classs
Try something like :
function removeProduct(myProduct){
$("a."+myProduct).css("display","none");
};
uses .css() to change the display property to none
or
function removeProduct(myProduct){
$("a."+myProduct).hide();
};
.hide() does the same thing as the .css() method does above
or
function removeProduct(myProduct){
$("a."+myProduct).addClass("yourclass");
};
where yourclass is a class you want to apply to an element.
And may I suggest you take a look at How jQuery works
Are you looking for this:
function removeProduct(myProduct){
$("a."+myProduct).addClass("display-none");
};
Separating the string selector from the variable
Try this if you want to hide the link on click event
$(function(){
$('#products a').on('click', function(e){
e.preventDefault();
$(this).hide();
});
});
A fiddle is here.
Suppose a HTML element's id is known, so the element can be refereced using:
document.getElementById(element_id);
Does a native Javascript function exist that can be used to append a CSS class to that element?
var element = document.getElementById(element_id);
element.className += " " + newClassName;
Voilà. This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).
Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.
In prototype, for instance:
// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);
See how much nicer that is?!
Adding class using element's classList property:
element.classList.add('my-class-name');
Removing:
element.classList.remove('my-class-name');
classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.
Not supported in IE < 10
When an element already has a class name defined, its influence on the element is tied to its position in the string of class names.
Later classes override earlier ones, if there is a conflict.
Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.
document.addClass= function(el, css){
var tem, C= el.className.split(/\s+/), A=[];
while(C.length){
tem= C.shift();
if(tem && tem!= css) A[A.length]= tem;
}
A[A.length]= css;
return el.className= A.join(' ');
}
You should be able to set the className property of the element. You could do a += to append it.
addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));
This will add ONE class or MULTIPLE classes :
addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"
you could use setAttribute.
Example:
For adding one class:
document.getElementById('main').setAttribute("class","classOne");
For multiple classes:
document.getElementById('main').setAttribute("class", "classOne classTwo");
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();
}