I know this is a silly question but how can I toggleClass() in a single line to both selectors.
$('.search-ico').click(function(){
$(this).toggleClass('is-active');
$('.class').toggleClass('is-active');
});
I tried below:
$('.search-ico').click(function(){
$(this,'.class').toggleClass('is-active');
});
but it's not working (only this is taking the class).
Thanks
you can use the .add method to combine string selectors and this.
https://api.jquery.com/add/
Use it like this:
$(this).add('.class').toggleClass(...)
Assuming the elements of class search-ico carry an id attribute, you can compose the selector string:
$("#" + $(this).attr('id') + ", .class").toggleClass("is-active")
note you can also add properties to the first object before adding a second object to it, and whatever property you add after the second object applies to all of them..
$(this).css('property','value').add('.class').toggleClass(...)
so here the css property of (this) is altered first.. before added to the second object, and then the toggleClass applied to all of them..
I try to add CSS class to <li> element, when I click on the button but addClass not working.
Here is my JS:
$('.test').click(function(event) {
var centrum1 = $('.p17');
$('section.bok-map').find( centrum1 ).addClass('active-region');
});
And this how is looking HTML code:
Where is the problem? find() returns true.
Here is demo: http://demo.vrs-factory.pl/mapDemo/
You had a couple of errors, as you were not selecting the correct element, hence the length of the selector was 0.
Firstly, the class is called pl7 not p17 and secondly, when using removeClass you don't put the . before the name of the class. As you are using removeClass it is understood that you want to target a class, hence not requiring you to specify this by adding the dot.
<script>
var centrum1 = $('.pl7');
$('.test').click(function(event) {
$('section.bok-map').find( centrum1 ).removeClass('pl7');
});
</script>
Also, it may be worth noting that since you are only referencing$(.pl7) once you do not necessarily have to assign it to a variable. You could also write it as below. It is up to you.
$('.test').click(function(event) {
$('section.bok-map').find('.pl7').removeClass('pl7');
});
This is my script
var newclass = 0;
jQuery("#addexperience").click(function(){
$("#expclone").clone().find("input:text").val("").end().prependTo( ".exp_clone" );
$(".ongoing").each(function(){
$(".ongoing").addClass("newclass"+newclass);
newclass++;
});
});
I am tring to clonning a perticular div, and add an class on clone element.
but addClass append every time,
means in first clone it added: newclass1, in second clone it added: newclass1 newclass2; so on..
i want only newclass2 in second clone, and newclass3 in thire clone and so on..
Try this,
var newclass = 0;
jQuery("#addexperience").click(function(){
$clone=$("#expclone").clone()
$clone.find("input:text").val("");
$clone.find(".ongoing").removeAttr('class') // remove all classes
.addClass('ongoing'); // again add ongoing class
$clone.find(".ongoing").each(function(){
$(this).addClass("newclass"+newclass);
newclass++;
});
$clone.prependTo(".exp_clone");
});
But, is is better to give an new id instead of new class.
You should use $(this) inside the callback of .each:
$(".ongoing").each(function(){
$(this).addClass("newclass"+newclass);
newclass++;
});
Or you even don't need the variable newclass, .addClass accept a function as parameter:
$(".ongoing").addClass(function(index) {
// index is start from 0
return "newclass" + (index + 1);
});
This is because every time you clone an element, it's going to add the class to each of those elements even though it is already present. What you do is, once you clone the element, get the last cloned element and addClass only for that. Remove the .each() function and try:
$(".ongoing").last().addClass('newClass'+newclass);
newclass++;
change this line:
$(".ongoing").addClass("newclass"+newclass);
to:
$(".ongoing").removeClass().addClass("newclass"+newclass);
it will remove all previous classes of .ongoing and add new class in it.
if you want to have .ongoing class then try like this:
$(".ongoing").removeClass().addClass("ongoing newclass"+newclass);
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.
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
}