How to Add a Class to a Given Element

How to add a class to a given element?

If you're only targeting modern browsers:

Use element.classList.add to add a class:

element.classList.add("my-class");

And element.classList.remove to remove a class:

element.classList.remove("my-class");

If you need to support Internet Explorer 9 or lower:

Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>

Then

var d = document.getElementById("div1");
d.className += " otherclass";

Note the space before otherclass. It's important to include the space otherwise it compromises existing classes that come before it in the class list.

See also element.className on MDN.

How can I add a class to a DOM element in JavaScript?

This answer was written/accepted a long time ago. Since then better, more comprehensive answers with examples have been submitted. You can find them by scrolling down. Below is the original accepted answer preserved for posterity.



new_row.className = "aClassName";

Here's more information on MDN: className

Add class to an element which gets loaded into a page

Did you try use complete callback in .load()

like this:

$(document).ready(function(){ 
$('#content').load("Header.html", function(){
// complete loading
$('#home').addClass('active')
});
});

If you use native js you don't need set dot (.) in classList.add('active') if you add dot you will get <div class=".active"></div>

How can I change an element's class with JavaScript?

Modern HTML5 Techniques for changing classes

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

if ( document.getElementById("MyElement").classList.contains('MyClass') )

document.getElementById("MyElement").classList.toggle('MyClass');

Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.

Simple cross-browser solution

The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

(You can use a space-delimited list to apply multiple classes.)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass";

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */

An explanation of this regex is as follows:

(?:^|\s) # Match the start of the string or any single whitespace character

MyClass # The literal text for the classname to remove

(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

To check if a class is already applied to an element:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )


### Assigning these actions to onclick events:

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onclick="this.className+=' MyClass'") this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:

<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onclick="changeClass()">My Button</button>

(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)

The second step is to move the onclick event out of the HTML and into JavaScript, for example using addEventListener

<script type="text/javascript">
function changeClass(){
// Code examples from above
}

window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>

(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)



JavaScript Frameworks and Libraries

The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.

Whilst some people consider it overkill to add a ~50  KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.

(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)

The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).

(Note that $ here is the jQuery object.)

Changing Classes with jQuery:

$('#MyElement').addClass('MyClass');

$('#MyElement').removeClass('MyClass');

if ( $('#MyElement').hasClass('MyClass') )

In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:

$('#MyElement').toggleClass('MyClass');


### Assigning a function to a click event with jQuery:
$('#MyElement').click(changeClass);

or, without needing an id:

$(':button:contains(My Button)').click(changeClass);


Add a class to a page element contained in a particular url

to check if a url contains any string, do the following:

if(window.location.href.indexOf(".com/poste") > -1) {
// do something
}

(checking if the index of a string is bigger than -1 is like asking if he is in there)

to conditonally add class:

element.classList.add("my-class");

combined it would be:

if(window.location.href.indexOf(".com/poste") > -1) {
titleClass = document.querySelector(".your-title-class");
titleClass.classList.add("conditionalClass");
}

*there are other solutions using jquery (like the one in @Wimanicesir comment), but it personaly prefer not using it :)

how to append a css class to an element by javascript?

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?!

add class to an element by clicking and remove it to the other elements By JavaScript

I modified your js code a bit. Let's do another loop in your click event listener, to uncheck the "active" class to every menu option.

var menu_link = document.querySelectorAll(".menu_option");

for(i=0; i<menu_link.length; i++){

var clicked = menu_link[i]

clicked.addEventListener("click", function(){

// modified in here

// clicked.classList.remove("active");

menu_link = document.querySelectorAll(".menu_option");

for (i = 0; i < menu_link.length; i++) {

menu_link[i].classList.remove("active");

}

this.classList.add("active");

});

}
* {

margin: 0;

padding: 0;

box-sizing: border-box;

}

html {

font-size: 100%;

}

body {

font-family: Arial, Helvetica, sans-serif;

color: #000000;

}

ul {

list-style: none;

}

a {

text-decoration: none;

color: #000000;

}

.container {

max-width: 900px;

margin: auto;

}

/*============================================================================

HEADER

===============================================================================*/

header {

background-color: #ffda00;

padding-top: 10px;

padding-bottom: 10px;

}

header nav {

display: flex;

align-items: center;

justify-content: space-between;

}

header nav ul li {

display: inline-block;

padding: 10px 20px;

border-radius: 5px;

}

header .logo {

font-size: 2rem;

}

header nav ul li a {

font-size: 1.1rem;

}

/* active menu */

.active {

background-color: #007bff;

}
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="css/styles.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/lykmapipo/themify-icons@0.1.2/css/themify-icons.css">

<title>My Store</title>

</head>

<body>

<header>

<div class="container">

<nav>

<span class="logo"><i class="ti-home"></i></span>

<ul>

<li class="menu_option"><a href="#">Users</a></li>

<li class="menu_option"><a href="#">Orders</a></li>

<li class="menu_option"><a href="#">Products</a></li>

<li class="menu_option"><a href="#">Exit</a></li>

</ul>

</nav>

</div>

</header>

<script src="js/script.js"></script>

</body>

</html>


Related Topics



Leave a reply



Submit