I'm curious about how can I add/remove class to html element? It seems to be a very simply operation. But it turned out that the method removeClass was not found for some reason.
So what I need to do is replace or remove an old one and add a new one to an element. How can I do that?
The removeClass method is included in jQuery, unless you've overridden it.
$("#someElement").removeClass("someclass");
Use AddClass to add class, removeClass to remove, toggleClass to toggle (removes class if exists or adds if does not exist) :)
If you use jQuery make sure it is loaded before your script and then use like this:
$('p').removeClass('myClass yourClass') // remove class
$("p").addClass("myClass yourClass"); // add class
if you want to use pure JS here you are : How do I add a class to a given element?
var d = document.getElementById("div1");
d.className = d.className + " otherclass";
Use addClass and removeClass
<div class="firstClass" id="uniqeId"></div>
$("div#uniqeId").removeClass("firstClass");
$("div#uniqeId").addClass("Some_Other_Class");
$('#elementId').addClass('className');
$('#elementId').removeClass('className');
See: http://api.jquery.com/category/manipulation/class-attribute/
Since your question is tagged with jquery, there are two functions you can use:
$(element).removeClass('oldclass')
$(element).addClass('newclass')
Without jQuery and on modern browsers you can work with the classList property:
element.classList.remove('oldclass')
element.classList.add('newclass')
You can use .toggleClass() to add/remove simultaneously, i mean switch from one class to another:
Description from the docs
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
if this is your html:
<div class="aaa">Some text.</div>
then this script:
$('div.aaa').toggleClass('bbb');
will output like this:
<div class="aaa bbb">Some text.</div>
Or if you do this:
$('elem').toggleClass('aaa bbb');
//--------------------^^^---here this class will be added/removed
Related
I'm trying to select the class p100 and replace it with a number that will be inputted by the user, does anyone know how to keep the "p" and replace the number in the class using jQuery?
<div class="c100 p100 small green storyline">
something like this can be done: $('.p100').removeClass('p100').addClass('p'+uservalue);
edit:
if you have more that one div with class p100:
$('.p100').each(function(){
$(this).removeClass('p100').addClass('p'+uservalue);
})
var item = $('.p100');
$('#button').click(() => {
item.removeClass('p100');
item.addClass('p200')
})
Working JSFiddle with visuals
You can set the class by using .attr(), like this:
$("#td_id").attr('class', 'newClass');
If you want to add a class, use .addclass() instead, like this:
$("#td_id").addClass('newClass');
Or a short way to swap classes using .toggleClass():
$("#td_id").toggleClass('change_me newClass');
Read more about Class attributes
While the other answers mention good ways with jquery, I'd like to add a vanilla javascript solution :) :
for(let elem of document.getElementsByClassName('p100'){
elem.classList.remove('p100');
elem.classList.add('p'+uservalue);
}
If you want to restrict it to divs (the above code will match every element with class p100) just replace document.getElementsByClassName('p100') with document.querySelectorAll('div .p100') :).
We could replace the two calls of .remove and .add with one call of .replace like this : elem.classList.replace('p100','p'+uservalue), Currently this function isn't implemented in all browsers.
Pay attention that classList is supported in IE10+, if you need IE9 support you need a polyfill, MDN already gives one and the polyfill provides replace function above too, see here : https://developer.mozilla.org/en-US/docs/Web/API/Element/classList (scroll down to see the polyfill)
for document.querySelectorAll support, it's supported in IE8(CSS2 selectors only) and IE9+(all CSS selectors including CSS3 ones).
Using String.match & RegExp.test
var pattern = new RegExp("/p[0-9]*/");
var className = $('div').attr('class')
if (pattern.test(className)) {
var class = className.match(pattern)[0];
$('div').removeClass(class).addClass('p' + integer);
}
Is there any alternative solution (in JavaScript) for document.getElementById(); to select a specific element, specifying both the class and id ?
for example I have such a content:
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="2"></div>
And I want to select the corresponding div under the "Question X" link in the function
function showQuestion(id)
{
var thediv = GetByClassAndId("q_content",id); // how to implement this function ?
WriteQuestionIn(thediv); //Ajax
}
Thanks in advance.
you can try document.querySelector()
like document.querySelector(".q_content#2") use the para like css selector..
Since ID is always unique (unless u make a mistake) u have no need to use both class and id to select the element.
Such an approach is not correct, and should be avoided at all cost.
What I suspect is your problem, is that the ID is only a number. Try adding a prefix which is a letter. Do view source to this page to see examples.
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="q1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="q2"></div>
function showQuestion(id)
{
var thediv = document.getElementById("q"+id);
WriteQuestionIn(thediv); //Ajax
}
Actually there is a function $ in jQuery for doing this operation. If you are using any framework, then you should remember there is always a jQuery library available. Else if you are using custom PHP, then add one of them like jQuery or other because they provide lots of types of selectors.
Now here is the code after adding jQuery:
$("#yourid") //basic selector
$("#yourid.yourclass").show()
Use .show() to show the selected element
Use .hide() To hide element
I am adding an element on a certain condition. But I don't want it suddenly appear but rather would like to slide it down. Here's how I add it:
$('.myDiv').after('<div>added content</div>');
How do I combine it with slideDown?
Try this instead :
$(".myDiv").after("<div style='display:none;'>added content</div>");
$(".myDiv").next("div").slideDown();
Good Luck !!
Try this out:
$('.myDiv').after('<div style="display:none">added content</div>').next().slideDown();
You need to use .next() on the div to which it is attached because .after()... adds the element as a sibling to the div to which it is added
Try this
$('.myDiv').after('<div style="display:none;" class="newDiv">New Content</div>');
$('.myDiv').next('.newDiv').slideDown();
first make sure the new content that you input is hidden using .newdiv{display:none;} either in your css file or inline code like: <div style="display:none;">
then use a callback function to only start after the code was inserted in the document when you used the after() method.
$('.myDiv').after('<div class="newdiv">added content</div>', function(){
$('.newdiv').slideDown();
});
Is it possible to put a javascript function call in place of a HTML class name so that the class can be set based upon the results of the function? For example, something like:
<a class="fSetClass(vName)" ....
which would call a function named fSetClass() and receive back a valid CSS class name based upon the parameter vName passed with it.
Thanks
No, it's not possible to do what you're asking from within the HTML. Though, you can use JavaScript to add the class to it afterward.
Smth like this, if in short way
document.onload = function(){
document.getElementById('your-element-id').className = fSetClass(vname);
}
No but what you can do is use jquery to get the item and then add or remove class names from it:
HTML
<div class="my-class">My Content</div>
jQuery
// will produce <div class="my-class added-class">My Content</div>
var addClass = 1;
if(addClass == 1) {
$(".my-class").addClass("added-class");
}
else
{
$(".my-class").removeClass("removed-class");
}
Only the on* event handler attributes are evaluated as JavaScript code, the other attributes are not.
As already said, you have to assign the class normally with JavaScript. Assuming you have a reference to the element (element), you have to assign the class to the className [MDN] property:
element.className = fSetClass(vname);
If you use jquery, you can set the class by using .attr():
$(document).ready(function() {
function fSetClass(vName){
$("#element_id").attr('class', vName);
}
fSetClass('className');
});
If you use jQuery, you can use the addClass function
$(element).addClass('add-this-class');
If you want to set the class instead, use attr:
$(element).attr('class','add-this-class');
Well, I know that with some jQuery actions, we can add a lot of classes to a particular div:
<div class="cleanstate"></div>
Let's say that with some clicks and other things, the div gets a lot of classes
<div class="cleanstate bgred paddingleft allcaptions ..."></div>
So, how I can remove all the classes except one? The only idea I have come up is with this:
$('#container div.cleanstate').removeClass().addClass('cleanstate');
While removeClass() kills all the classes, the div get screwed up, but adding just after that addClass('cleanstate') it goes back to normal. The other solution is to put an ID attribute with the base CSS properties so they don't get deleted, what also improves performance, but i just want to know another solution to get rid of all except ".cleanstate"
I'm asking this because, in the real script, the div suffers various changes of classes.
Instead of doing it in 2 steps, you could just reset the entire value at once with attr by overwriting all of the class values with the class you want:
jQuery('#container div.cleanstate').attr('class', 'cleanstate');
Sample: http://jsfiddle.net/jtmKK/1/
Use attr to directly set the class attribute to the specific value you want:
$('#container div.cleanstate').attr('class','cleanstate');
With plain old JavaScript, not JQuery:
document.getElementById("container").className = "cleanstate";
Sometimes you need to keep some of the classes due to CSS animation, because as soon as you remove all classes, animation may not work. Instead, you can keep some classes and remove the rest like this:
$('#container div.cleanstate').removeClass('removethis removethat').addClass('cleanstate');
regarding to robs answer and for and for the sake of completeness you can also use querySelector with vanilla
document.querySelector('#container div.cleanstate').className = "cleanstate";
What if if you want to keep one or more than one classes and want classes except these. These solution would not work where you don't want to remove all classes add that perticular class again.
Using attr and removeClass() resets all classes in first instance and then attach that perticular class again. If you using some animation on classes which are being reset again, it will fail.
If you want to simply remove all classes except some class then this is for you.
My solution is for: removeAllExceptThese
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
$.fn.removeClassesExceptThese = function(classList) {
/* pass mutliple class name in array like ["first", "second"] */
var $elem = $(this);
if($elem.length > 0) {
var existingClassList = $elem.attr("class").split(' ');
var classListToRemove = existingClassList.diff(classList);
$elem
.removeClass(classListToRemove.join(" "))
.addClass(classList.join(" "));
}
return $elem;
};
This will not reset all classes, it will remove only necessary.
I needed it in my project where I needed to remove only not matching classes.
You can use it $(".third").removeClassesExceptThese(["first", "second"]);