TutorialsTonight Logo

JAVASCRIPT ASSIGNMENT OPERATORS

In this tutorial, you will learn about all the different assignment operators in javascript and how to use them in javascript.

Assignment Operators

In javascript, there are 16 different assignment operators that are used to assign value to the variable. It is shorthand of other operators which is recommended to use.

The assignment operators are used to assign value based on the right operand to its left operand.

The left operand must be a variable while the right operand may be a variable, number, boolean, string, expression, object, or combination of any other.

One of the most basic assignment operators is equal = , which is used to directly assign a value.

javascript assignment operator

Assignment Operators List

Here is the list of all assignment operators in JavaScript:

In the following table if variable a is not defined then assume it to be 10.

Operator Description Example Equivalent to
= a = 10 a = 10
+= a += 10 a = a + 10
-= a -= 10 a = a - 10
*= a *= 10 a = a * 10
/= a /= 10 a = a / 10
%= a %= 10 a = a % 10
**= a **= 2 a = a ** 2
<<= a <<= 1 a = a << 1
>>= a >>= 2 a = a >> 2
>>>= a >>>= 1 a = a >>> 1
&= a &= 4 a = a & 4
|= a |= 2 a = a | 2
^= a ^= 5 a = a ^ 5
&&= a &&= 3 a = a && 3
||= a ||= 4 a = a || 4
??= a ??= 2 a = a ?? 2

Assignment operator

The assignment operator = is the simplest value assigning operator which assigns a given value to a variable.

The assignment operators support chaining, which means you can assign a single value in multiple variables in a single line.

Addition assignment operator

The addition assignment operator += is used to add the value of the right operand to the value of the left operand and assigns the result to the left operand.

On the basis of the data type of variable, the addition assignment operator may add or concatenate the variables.

Subtraction assignment operator

The subtraction assignment operator -= subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.

If the value can not be subtracted then it results in a NaN .

Multiplication assignment operator

The multiplication assignment operator *= assigns the result to the left operand after multiplying values of the left and right operand.

Division assignment operator

The division assignment operator /= divides the value of the left operand by the value of the right operand and assigns the result to the left operand.

Remainder assignment operator

The remainder assignment operator %= assigns the remainder to the left operand after dividing the value of the left operand by the value of the right operand.

Exponentiation assignment operator

The exponential assignment operator **= assigns the result of exponentiation to the left operand after exponentiating the value of the left operand by the value of the right operand.

Left shift assignment

The left shift assignment operator <<= assigns the result of the left shift to the left operand after shifting the value of the left operand by the value of the right operand.

Right shift assignment

The right shift assignment operator >>= assigns the result of the right shift to the left operand after shifting the value of the left operand by the value of the right operand.

Unsigned right shift assignment

The unsigned right shift assignment operator >>>= assigns the result of the unsigned right shift to the left operand after shifting the value of the left operand by the value of the right operand.

Bitwise AND assignment

The bitwise AND assignment operator &= assigns the result of bitwise AND to the left operand after ANDing the value of the left operand by the value of the right operand.

Bitwise OR assignment

The bitwise OR assignment operator |= assigns the result of bitwise OR to the left operand after ORing the value of left operand by the value of the right operand.

Bitwise XOR assignment

The bitwise XOR assignment operator ^= assigns the result of bitwise XOR to the left operand after XORing the value of the left operand by the value of the right operand.

Logical AND assignment

The logical AND assignment operator &&= assigns value to left operand only when it is truthy .

Note : A truthy value is a value that is considered true when encountered in a boolean context.

Logical OR assignment

The logical OR assignment operator ||= assigns value to left operand only when it is falsy .

Note : A falsy value is a value that is considered false when encountered in a boolean context.

Logical nullish assignment

The logical nullish assignment operator ??= assigns value to left operand only when it is nullish ( null or undefined ).

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types

JavaScript Operators

  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript Comparison and Logical Operators

JavaScript Ternary Operator

JavaScript Booleans

JavaScript Bitwise Operators

  • JavaScript Object.is()
  • JavaScript typeof Operator

JavaScript operators are special symbols that perform operations on one or more operands (values). For example,

Here, we used the + operator to add the operands 2 and 3 .

JavaScript Operator Types

Here is a list of different JavaScript operators you will learn in this tutorial:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • String Operators
  • Miscellaneous Operators

1. JavaScript Arithmetic Operators

We use arithmetic operators to perform arithmetic calculations like addition, subtraction, etc. For example,

Here, we used the - operator to subtract 3 from 5 .

Commonly Used Arithmetic Operators

Operator Name Example
Addition
Subtraction
Multiplication
Division
Remainder
Increment (increments by ) or
Decrement (decrements by ) or
Exponentiation (Power)

Example 1: Arithmetic Operators in JavaScript

Note: The increment operator ++ adds 1 to the operand. And, the decrement operator -- decreases the value of the operand by 1 .

To learn more, visit Increment ++ and Decrement -- Operators .

2. JavaScript Assignment Operators

We use assignment operators to assign values to variables. For example,

Here, we used the = operator to assign the value 5 to the variable x .

Commonly Used Assignment Operators

Operator Name Example
Assignment Operator
Addition Assignment
Subtraction Assignment
Multiplication Assignment
Division Assignment
Remainder Assignment
Exponentiation Assignment

Example 2: Assignment Operators in JavaScript

3. javascript comparison operators.

We use comparison operators to compare two values and return a boolean value ( true or false ). For example,

Here, we have used the > comparison operator to check whether a (whose value is 3 ) is greater than b (whose value is 2 ).

Since 3 is greater than 2 , we get true as output.

Note: In the above example, a > b is called a boolean expression since evaluating it results in a boolean value.

Commonly Used Comparison Operators

Operator Meaning Example
Equal to gives us
Not equal to gives us
Greater than gives us
Less than gives us
Greater than or equal to gives us
Less than or equal to gives us
Strictly equal to gives us
Strictly not equal to gives us

Example 3: Comparison Operators in JavaScript

The equality operators ( == and != ) convert both operands to the same type before comparing their values. For example,

Here, we used the == operator to compare the number 3 and the string 3 .

By default, JavaScript converts string 3 to number 3 and compares the values.

However, the strict equality operators ( === and !== ) do not convert operand types before comparing their values. For example,

Here, JavaScript didn't convert string 4 to number 4 before comparing their values.

Thus, the result is false , as number 4 isn't equal to string 4 .

4. JavaScript Logical Operators

We use logical operators to perform logical operations on boolean expressions. For example,

Here, && is the logical operator AND . Since both x < 6 and y < 5 are true , the combined result is true .

Commonly Used Logical Operators

Operator Syntax Description
(Logical AND) only if both and are
(Logical OR) if either or is
(Logical NOT) if is and vice versa

Example 4: Logical Operators in JavaScript

Note: We use comparison and logical operators in decision-making and loops. You will learn about them in detail in later tutorials.

More on JavaScript Operators

We use bitwise operators to perform binary operations on integers.

Operator Description Example
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Sign-propagating right shift
>>> Zero-fill right shift

Note: We rarely use bitwise operators in everyday programming. If you are interested, visit JavaScript Bitwise Operators to learn more.

In JavaScript, you can also use the + operator to concatenate (join) two strings. For example,

Here, we used the + operator to concatenate str1 and str2 .

JavaScript has many more operators besides the ones we listed above. You will learn about them in detail in later tutorials.

Operator Description Example
: Evaluates multiple operands and returns the value of the last operand.
: Returns value based on the condition.
Returns the data type of the variable.
Returns t if the specified object is a valid object of the specified class.
Discards any expression's return value.

Table of Contents

  • Introduction
  • JavaScript Arithmetic Operators
  • JavaScript Assignment Operators
  • JavaScript Comparison Operators
  • JavaScript Logical Operators

Video: JavaScript Operators

Sorry about that.

Related Tutorials

JavaScript Tutorial

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.

Similarly, you can destructure objects on the left-hand side of the assignment.

This capability is similar to features present in languages such as Perl and Python.

For features specific to array or object destructuring, refer to the individual examples below.

Binding and assignment

For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.

In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.

All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let , once with const .

In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:

  • The looping variable of for...in for...of , and for await...of loops;
  • Function parameters;
  • The catch binding variable.

In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let , or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.

Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .

If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.

Note that the equivalent binding pattern of the code above is not valid syntax:

You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .

Default value

Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .

The default value can be any expression. It will only be evaluated when necessary.

Rest property

You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.

The rest property must be the last in the pattern, and must not have a trailing comma.

Array destructuring

Basic variable assignment, destructuring with more elements than the source.

In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

Ignoring some returned values

You can ignore return values that you're not interested in:

You can also ignore all returned values:

Using a binding pattern as the rest property

The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.

These binding patterns can even be nested, as long as each rest property is the last in the list.

On the other hand, object destructuring can only have an identifier as the rest property.

Unpacking values from a regular expression match

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

Using array destructuring on any iterable

Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.

Non-iterables cannot be destructured as arrays.

Iterables are only iterated until all bindings are assigned.

The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.

Object destructuring

Basic assignment, assigning to new variable names.

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .

Assigning to new variable names and providing default values

A property can be both

  • Unpacked from an object and assigned to a variable with a different name.
  • Assigned a default value in case the unpacked value is undefined .

Unpacking properties from objects passed as a function parameter

Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.

Consider this object, which contains information about a user.

Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.

You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.

Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .

Setting a function parameter's default value

Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.

Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.

In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .

You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.

For more information, see Default parameters > Destructured parameter with default value assignment .

Nested object and array destructuring

For of iteration and destructuring, computed object property names and destructuring.

Computed property names, like on object literals , can be used with destructuring.

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.

Destructuring primitive values

Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.

Same as accessing properties, destructuring null or undefined throws a TypeError .

This happens even when the pattern is empty.

Combined array and object destructuring

Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

The prototype chain is looked up when the object is deconstructed

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

Specifications

Specification

Destructuring assignment

The two most used data structures in JavaScript are Object and Array .

  • Objects allow us to create a single entity that stores data items by key.
  • Arrays allow us to gather data items into an ordered list.

However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.

Array destructuring

Here’s an example of how an array is destructured into variables:

Now we can work with variables instead of array members.

It looks great when combined with split or other array-returning methods:

As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.

It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.

It’s just a shorter way to write:

Unwanted elements of the array can also be thrown away via an extra comma:

In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).

…Actually, we can use it with any iterable, not only arrays:

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.

We can use any “assignables” on the left side.

For instance, an object property:

In the previous chapter, we saw the Object.entries(obj) method.

We can use it with destructuring to loop over the keys-and-values of an object:

The similar code for a Map is simpler, as it’s iterable:

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

The rest ‘…’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.

Default values

If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:

If we want a “default” value to replace the missing one, we can provide it using = :

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

For instance, here we use the prompt function for two defaults:

Please note: the prompt will run only for the missing value ( surname ).

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .

For instance:

Properties options.title , options.width and options.height are assigned to the corresponding variables.

The order does not matter. This works too:

The pattern on the left side may be more complex and specify the mapping between properties and variables.

If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:

The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.

For potentially missing properties we can set default values using "=" , like this:

Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.

In the code below prompt asks for width , but not for title :

We also can combine both the colon and equality:

If we have a complex object with many properties, we can extract only what we need:

The rest pattern “…”

What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?

We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.

It looks like this:

In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.

This won’t work:

The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:

So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.

To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :

Nested destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:

All properties of options object except extra which is absent in the left part, are assigned to corresponding variables:

Finally, we have width , height , item1 , item2 and title from the default value.

Note that there are no variables for size and items , as we take their content instead.

Smart function parameters

There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on.

Here’s a bad way to write such a function:

In real-life, the problem is how to remember the order of arguments. Usually, IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.

That’s ugly. And becomes unreadable when we deal with more parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

We can also use more complex destructuring with nested objects and colon mappings:

The full syntax is the same as for a destructuring assignment:

Then, for an object of parameters, there will be a variable varName for the property incomingProperty , with defaultValue by default.

Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:

We can fix this by making {} the default value for the whole object of parameters:

In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.

Destructuring assignment allows for instantly mapping an object or array onto many variables.

The full object syntax:

This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.

Object properties that have no mapping are copied to the rest object.

The full array syntax:

The first item goes to item1 ; the second goes into item2 , and all the rest makes the array rest .

It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.

We have an object:

Write the destructuring assignment that reads:

  • name property into the variable name .
  • years property into the variable age .
  • isAdmin property into the variable isAdmin (false, if no such property)

Here’s an example of the values after your assignment:

The maximal salary

There is a salaries object:

Create the function topSalary(salaries) that returns the name of the top-paid person.

  • If salaries is empty, it should return null .
  • If there are multiple top-paid persons, return any of them.

P.S. Use Object.entries and destructuring to iterate over key/value pairs.

Open a sandbox with tests.

Open the solution with tests in a sandbox.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

40 JavaScript Projects for Beginners – Easy Ideas to Get Started Coding JS

Jessica Wilkins

The best way to learn a new programming language is to build projects.

I have created a list of 40 beginner friendly project tutorials in Vanilla JavaScript, React, and TypeScript.

My advice for tutorials would be to watch the video, build the project, break it apart and rebuild it your own way. Experiment with adding new features or using different methods.

That will test if you have really learned the concepts or not.

You can click on any of the projects listed below to jump to that section of the article.

Vanilla JavaScript Projects

How to create a color flipper.

  • How to create a counter
  • How to create a review carousel
  • How to create a responsive navbar
  • How to create a sidebar
  • How to create a modal

How to create a FAQ page

How to create a restaurant menu page, how to create a video background, how to create a navigation bar on scroll, how to create tabs that display different content, how to create a countdown clock, how to create your own lorem ipsum, how to create a grocery list, how to create an image slider, how to create a rock paper scissors game, how to create a simon game, how to create a platformer game.

  • How to create Doodle Jump
  • How to create Flappy Bird
  • How to create a Memory game
  • How to create a Whack-a-mole game
  • How to create Connect Four game
  • How to create a Snake game
  • How to create a Space Invaders game
  • How to create a Frogger game
  • How to create a Tetris game

React Projects

How to build a tic-tac-toe game using react hooks, how to build a tetris game using react hooks, how to create a birthday reminder app.

  • How to create a tours page

How to create an accordion menu

How to create tabs for a portfolio page, how to create a review slider, how to create a color generator, how to create a stripe payment menu page, how to create a shopping cart page, how to create a cocktail search page, typescript projects, how to build a quiz app with react and typescript, how to create an arkanoid game with typescript.

If you have not learned JavaScript fundamentals, then I would suggest watching this course before proceeding with the projects.

Many of the screenshots below are from here .

Image

In this John Smilga tutorial , you will learn how to create a random background color changer. This is a good project to get you started working with the DOM.

In Leonardo Maldonado's article on why it is important to learn about the DOM, he states:

By manipulating the DOM, you have infinite possibilities. You can create applications that update the data of the page without needing a refresh. Also, you can create applications that are customizable by the user and then change the layout of the page without a refresh.

Key concepts covered:

  • document.getElementById()
  • document.querySelector()
  • addEventListener()
  • document.body.style.backgroundColor
  • Math.floor()
  • Math.random()
  • array.length

Before you get started, I would suggest watching the introduction where John goes over how to access the setup files for all of his projects.

How to create a Counter

Image

In this John Smilga tutorial , you will learn how to create a counter and write conditions that change the color based on positive or negative numbers displayed.

This project will give you more practice working with the DOM and you can use this simple counter in other projects like a pomodoro clock.

  • document.querySelectorAll()
  • currentTarget property
  • textContent

How to create a Review carousel

Image

In this tutorial , you will learn how to create a carousel of reviews with a button that generates random reviews.

This is a good feature to have on an ecommerce site to display customer reviews or a personal portfolio to display client reviews.

  • DOMContentLoaded

How to create a responsive Navbar

Image

In this tutorial , you will learn how to create a responsive navbar that will show the hamburger menu for smaller devices.

Learning how to develop responsive websites is an important part of being a web developer. This is a popular feature used on a lot of websites.

  • classList.toggle()

How to create a Sidebar

Image

In this tutorial , you will learn how to create a sidebar with animation.

This is a cool feature that you can add to your personal website.

  • classList.remove()

How to create a Modal

Image

In this tutorial , you will learn how to create a modal window which is used on websites to get users to do or see something specific.

A good example of a modal window would be if a user made changes in a site without saving them and tried to go to another page. You can create a modal window that warns them to save their changes or else that information will be lost.

  • classList.add()

Image

In this tutorial , you will learn how to create a frequently asked questions page which educates users about a business and drives traffic to the website through organic search results.

Image

In this tutorial , you will learn how to make a restaurant menu page that filters through the different food menus. This is a fun project that will teach you higher order functions like map, reduce, and filter.

In Yazeed Bzadough's article on higher order functions, he states:

the greatest benefit of HOFs is greater reusability.
  • map, reduce, and filter
  • includes method

Image

In this tutorial , you will learn how to make a video background with a play and pause feature. This is a common feature found in a lot of websites.

  • classList.contains()

Image

In this tutorial , you will learn how to create a navbar that slides down when scrolling and then stays at a fixed position at a certain height.

This is a popular feature found on many professional websites.

  • getFullYear()
  • getBoundingClientRect()
  • slice method
  • window.scrollTo()

Image

In this tutorial , you will learn how to create tabs that will display different content which is useful when creating single page applications.

Image

In this tutorial , you will learn how to make a countdown clock which can be used when a new product is coming out or a sale is about to end on an ecommerce site.

  • setInterval()
  • clearInterval()

Image

In this tutorial , you will learn how to create your own Lorem ipsum generator.

Lorem ipsum is the go to placeholder text for websites. This is a fun project to show off your creativity and create your own text.

  • event.preventDefault()

Image

In this tutorial , you will learn how to update and delete items from a grocery list and create a simple CRUD (Create, Read, Update, and Delete) application.

CRUD plays a very important role in developing full stack applications. Without it, you wouldn't be able to do things like edit or delete posts on your favorite social media platform.

  • createAttribute()
  • setAttributeNode()
  • appendChild()

Image

In this tutorial , you will learn how to build an image slider that you can add to any website.

  • querySelectorAll()
  • if/else statements

Image

In this tutorial , Tenzin will teach you how to create a Rock Paper Scissors game. This is a fun project that will give more practice working with the DOM.

  • switch statements

Image

In this tutorial , Beau Carnes will teach you how to create the classic Simon Game. This is a good project that will get you thinking about the different components behind the game and how you would build out each of those functionalities.

  • querySelector()
  • setTimeout()

Image

In this tutorial , Frank Poth will teach you how to build a platformer game. This project will introduce you to Object Oriented Programming principles and the Model, View, Controller software pattern.

  • this keyword
  • OOP principles
  • MVC pattern

How to create Doodle Jump and Flappy Bird

Image

In this video series , Ania Kubow will teach you how to build Doodle Jump and Flappy Bird .

Building games are a fun way to learn more about JavaScript and will cover many popular JavaScript methods.

  • createElement()
  • removeChild()
  • removeEventListener()

How to create seven classic games with Ania Kubow

Image

You will have a lot of fun creating seven games in this course by Ania Kubow:

  • Memory Game
  • Whack-a-mole
  • Connect Four
  • Space Invaders
  • onclick event
  • arrow functions

If you are not familiar with React fundamentals, then I would suggest taking this course before proceeding with the projects.

Image

In this freeCodeCamp article , Per Harald Borgen talks about Scrimba's Tic-Tac-Toe game tutorial led by Thomas Weibenfalk. You can view the video course on Scimba's YouTube Channel.

This is a good project to start getting comfortable with React basics and working with hooks.

  • import / export

Image

In this tutorial , Thomas Weibenfalk will teach you how to build a Tetris game using React Hooks and styled components.

  • useEffect()
  • useCallback()
  • styled components

Image

In this John Smilga course, you will learn how to create a birthday reminder app. This is a good project to start getting comfortable with React basics and working with hooks.

I would also suggest watching John's video on the startup files for this project.

How to create a Tours Page

Image

In this tutorial , you will learn how to create a tours page where the user can delete which tours they are not interested in.

This will give you practice with React hooks and the async/await pattern.

  • try...catch statement
  • async/await pattern

Image

In this tutorial , you will learn how to create a questions and answers accordion menu. These menus can be helpful in revealing content to users in a progressive way.

  • React icons

Image

In this tutorial , you will learn how to create tabs for a mock portfolio page. Tabs are useful when you want to display different content in single page applications.

Image

In this tutorial , you will learn how to create a review slider that changes to a new review every few seconds.

This is a cool feature that you can incorporate into an ecommerce site or portfolio.

Image

In this tutorial , you will learn how to create a color generator. This is a good project to continue practicing working with hooks and setTimeout.

  • clearTimeout()

Image

In this tutorial , you will learn how to create a Stripe payment menu page. This project will give you good practice on how to design a product landing page using React components.

  • useContext()

Image

In this tutorial , you will learn how to create a shopping cart page that updates and deletes items. This project will also be a good introduction to the useReducer hook.

  • <svg> elements
  • useReducer()

Image

In this tutorial , you will learn how to create a cocktail search page. This project will give you an introduction to how to use React router.

React router gives you the ability to create a navigation on your website and change views to different components like an about or contact page.

  • <Router>
  • <Switch>

If you are unfamiliar with TypeScript, then I would suggest watching this course before proceeding with this project.

Image

In this tutorial , Thomas Weibenfalk will teach you how to build a quiz app with React and TypeScript. This is a good opportunity to practice the basics of TypeScript.

  • dangerouslySetInnerHTML

Image

In this tutorial , Thomas Weibenfalk will teach you how to build the classic Arkanoid game in TypeScript. This is a good project that will give you practice working with the basic concepts for TypeScript.

  • HTMLCanvasElement

I hope you enjoy this list of 40 project tutorials in Vanilla JavaScript, React and TypeScript.

Happy coding!

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript tutorial.

JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advanced.

Examples in Each Chapter

With our "Try it Yourself" editor, you can edit the source code and view the result.

My First JavaScript

Try it Yourself »

Use the Menu

We recommend reading this tutorial, in the sequence listed in the menu.

If you have a large screen, the menu will always be present on the left.

If you have a small screen, open the menu by clicking the top menu sign ☰ .

Learn by Examples

Examples are better than 1000 words. Examples are often easier to understand than text explanations.

This tutorial supplements all explanations with clarifying "Try it Yourself" examples.

If you try all the examples, you will learn a lot about JavaScript, in a very short time!

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

   1. HTML to define the content of web pages

   2. CSS to specify the layout of web pages

   3. JavaScript to program the behavior of web pages

This tutorial covers every version of JavaScript:

  • The Original JavaScript ES1 ES2 ES3 (1997-1999)
  • The First Main Revision ES5 (2009)
  • The Second Revision ES6 (2015)
  • The Yearly Additions (2016, 2017 ... 2021, 2022)

Advertisement

Learning Speed

In this tutorial, the learning speed is your choice.

Everything is up to you.

If you are struggling, take a break, or re-read the material.

Always make sure you understand all the "Try-it-Yourself" examples.

The only way to become a clever programmer is to: Practice. Practice. Practice. Code. Code. Code !

Test Yourself With Exercises

Create a variable called carName and assign the value Volvo to it.

Start the Exercise

Commonly Asked Questions

  • How do I get JavaScript?
  • Where can I download JavaScript?
  • Is JavaScript Free?

You don't have to get or download JavaScript.

JavaScript is already running in your browser on your computer, on your tablet, and on your smart-phone.

JavaScript is free to use for everyone.

My Learning

Track your progress with the free "My Learning" program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study at W3Schools without using My Learning.

Track your progress with at W3Schools.com

JavaScript References

W3Schools maintains a complete JavaScript reference, including all HTML and browser objects.

The reference contains examples for all properties, methods and events, and is continuously updated according to the latest web standards.

JavaScript Quiz Test

Test your JavaScript skills at W3Schools!

Start JavaScript Quiz!

JavaScript Exam - Get Your Diploma!

Kickstart your career.

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

assignment through javascript

  • Election 2024
  • Entertainment
  • Newsletters
  • Photography
  • AP Buyline Personal Finance
  • AP Buyline Shopping
  • Press Releases
  • Israel-Hamas War
  • Russia-Ukraine War
  • Global elections
  • Asia Pacific
  • Latin America
  • Middle East
  • Delegate Tracker
  • AP & Elections
  • College football
  • Auto Racing
  • Movie reviews
  • Book reviews
  • Financial Markets
  • Business Highlights
  • Financial wellness
  • Artificial Intelligence
  • Social Media

South Carolina considers its energy future through state Senate committee

Image

Dominion Energy South Carolina President Keller Kissam, left , and Duke Energy’s utility operations in South Carolina President Mike Callahan, speak before testifying before a South Carolina Senate committee planning to write a comprehensive energy bill in 2025 in Columbia, S.C., on Thursday, Aug. 22 2024. (AP Photo/Jeffrey Collins)

South Carolina Senate President Thomas Alexander, R-Walhalla, left; Senate Majority Leader Shane Massey, R-Edgefield, center; and Sen. Nikki Setlzer, D- West Columbia, right, speak before a South Carolina Senate committee planning to write a comprehensive energy bill in 2025 in Columbia, S.C., on Thursday, Aug. 22 2024. (AP Photo/Jeffrey Collins)

Santee Cooper CEO Jimmy Staton, left, Dominion Energy South Carolina President Keller Kissam, center, and Duke Energy’s utility operations in South Carolina President Mike Callahan, right, are sworn in before testifying before a South Carolina Senate committee planning to write a comprehensive energy bill in 2025. in Columbia, S.C., on Thursday, Aug. 22 2024. (AP Photo/Jeffrey Collins)

Santee Cooper CEO Jimmy Staton, left, Dominion Energy South Carolina President Keller Kissam, center, and Duke Energy’s utility operations in South Carolina President Mike Callahan, right, wait to testify before a South Carolina Senate committee planning to write a comprehensive energy bill in 2025 in Columbia, S.C., on Thursday, Aug. 22 2024. (AP Photo/Jeffrey Collins)

Duke Energy’s utility operations in South Carolina President Mike Callahan waits to testify before a South Carolina Senate committee planning to write a comprehensive energy bill in 2025 in Columbia, S.C., on Thursday, Aug. 22 2024. (AP Photo/Jeffrey Collins)

  • Copy Link copied

Image

COLUMBIA, S.C. (AP) — The South Carolina Senate on Thursday started its homework assignment of coming up with a comprehensive bill to guide energy policy in a rapidly growing state and amid a quickly changing power- generation world.

The Special Committee on South Carolina’s Energy Future plans several meetings through October. On Thursday, the committee heard from the leaders of the state’s three major utilities. Future meetings will bring in regular ratepayers, environmentalists, business leaders and experts on the latest technology to make electricity,

The Senate took this task upon itself. They put the brakes a massive 80-plus page energy overhaul bill that passed the House in March in less than six weeks, and the bill died at the end of the session.

Many senators said the process earlier this year was rushed . They remembered the last time they trusted an overhaul bill backed by utilities.

State-owned Santee Cooper and private South Carolina Electric & Gas used those rules passed 15 years ago to put ratepayers on the hook for billions of dollars spent on two new nuclear reactors that never generated a watt of power before construction was abandoned because of rising costs.

Image

But those dire memories are being mixed with dire predictions of a state running out of power.

Unusually cold weather on Christmas Eve 2022 along with problems at a generating facility nearly led to rolling blackouts in South Carolina. Demand from advanced manufacturing and data centers is rising. If electric cars grow in popularity, more power is needed. And a state that added 1.3 million people since 2000 has a lot more air conditioners, washing machines and charges for devices, the utility leaders said.

Senators stopped Duke Energy’s president in South Carolina, Mike Callahan, in middle of his presentation after he told them his utility’s most recent predictions for growth in electricity usage over the rest of this decade were eight times more than they were just two years ago.

“Growth is here, and much more is coming. We need clear energy policy to plan for that growth,” Callahan said,

The utility leaders told senators their companies need to know what kind of sources of power — natural gas, solar, nuclear, wind or others — the state wants to emphasize. They would like to have a stable rules from regulators on how they operate.

“A quick no is a lot better to us than a long-term maybe,” Santee Cooper CEO Jimmy Staton said.

Another complicating factor are federal rules that may require utilities to shut down power plants that use coal before there are replacements with different sources online, Staton said.

Others aren’t so sure the state needs a rapid increase in power generation. Environmentalists have suggested the 2022 problems that led to blackouts were made worse because power plants were nowhere near capacity and better cooperation in the grid would allow electricity to get to where its needed easier.

Those less bullish on the overhaul also are urging the state not to lock in on one source of power over another because technology could leave South Carolina with too much power generation in inefficient ways.

There will likely be plenty of discussion of data centers that use a lot of electricity without the number of jobs, property taxes or other benefits a manufacturer provides.

Staton estimated about 70% of Santee Cooper’s increased demand is from data centers.

“We clearly need them. I don’t want to go back in time,” committee chairman Republican Senate Majority Leader Shane Massey said. “What I’m trying to get at is a better understanding, a better handle on how much of the projected growth is based on data centers or on everything else.”

Massey has been hard on Dominion Energy, which bought South Carolina Electric & Gas after the abandoned nuclear project at the V.C. Summer Nuclear Station. But Dominion Energy South Carolina President Keller Kissam said it is important that all options, including a new nuclear plant, remain on the table.

“Everybody thinks if we build anything that we’re going to absolutely repeat what we did with V.C. Summer” Kissam said. “Well, I promise you, that ain’t gonna happen. OK? I’ll pack up and leave.”

Massey said he appreciated Kissam’s candor and felt he was a straight shooter, but there are a lot of other people involved in the failed project who lied and hid problems.

“I can’t put that behind me. And I don’t think a lot of people can put that behind them,” Massey said.

Massey’s goal is to have a bill ready by the time the 2025 session starts in January.

Image

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How to add a class to a given element?

I have an element that already has a class:

Now, I want to create a JavaScript function that will add a class to the div (not replace, but add).

How can I do that?

  • dom-manipulation

Alexander Abakumov's user avatar

  • 84 To anyone reading this thread in 2020 or later, skip the old className method and use element.classList.add("my-class") instead. –  Pikamander2 Commented Jan 3, 2020 at 4:33

28 Answers 28

If you're only targeting modern browsers:.

Use element.classList.add to add a class:

And element.classList.remove to remove a 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.

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 .

laurent's user avatar

  • 30 If the only work on the whole page that needs to be done with JavaScript is this class name addition, then yes. But I can't see this being the only dynamic part of the page. A library will help with everything else as well. At 30-50kb jQuery is hardly a hit worth discussing. –  rfunduk Commented Feb 3, 2009 at 14:59
  • 196 "A library will help with everything else as well" - apart from learning JavaScript –  meouw Commented Feb 3, 2009 at 15:24
  • 21 What does adding a class to a DOM element have to do with learning the language? document.getElementById('div1').className is as much a library related issue as using jQuery to do the same is. The question was "how can I do that", a thoroughly tested library is the sensible answer. –  rfunduk Commented Feb 3, 2009 at 20:06
  • 12 @thenduks: I'm sure you know that JavaScript !== jQuery. It's a good thing that the answers to this question include library and non library solutions because it is important to know how things work not just the simplest way to accomplish them. You'll notice this question is tagged javascript –  meouw Commented Feb 3, 2009 at 20:25
  • 4 @meouw: I agree with you. jQuery is written in JavaScript, however, so I maintain that mentioning to the OP that a library is a good idea is not 'pushing a framework down [his] throat'. That's all. –  rfunduk Commented Feb 4, 2009 at 19:59

The easiest way to do this without any framework is to use element.classList.add method.

Edit: And if you want to remove class from an element -

I prefer not having to add any empty space and duplicate entry handling myself (which is required when using the document.className approach). There are some browser limitations , but you can work around them using polyfills .

Moazzam Khan's user avatar

  • 69 It's a shame that this isn't supported prior to IE 10.0 because it's an excellent feature and the easiest solution to an issue I come across often. –  mricci Commented Jan 14, 2013 at 4:18
  • 12 A polyfill for classList is available. –  wcandillon Commented Aug 4, 2013 at 16:24
  • 10 element.classList docs on MDN. –  willlma Commented Mar 26, 2014 at 1:15
  • 11 This one seems to be the best one to use, as the ones with space at least feel like hacks - not ment for adding classes... –  Silver Ringvee Commented Dec 18, 2015 at 7:26
  • 5 @SilverRingvee A further risk of the space approach is that some other developer might not know it's vital, and remove it in order to clean things up. –  akauppi Commented Aug 3, 2016 at 8:23

find your target element "d" however you wish and then:

you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..

Cœur's user avatar

  • 1 And to remove using this method? –  DeathGrip Commented Dec 22, 2017 at 11:30
  • 3 @DeathGrip simply set the class back to a single defined name d.className = 'originalClass'; –  TheTechy Commented Dec 26, 2017 at 10:10
  • 1 @TheTechy - if you have more than one class you need to keep (which happens a lot these days), that will not work. –  Mark Schultheiss Commented Apr 1, 2019 at 10:51
  • 1 To remove the old-fashioned way, split the classname on whitespace, remove the one you don't want from the resulting array, then join the array again... or use element.classList.remove . –  Stijn de Witt Commented Aug 14, 2019 at 16:41

Cross Compatible

In the following example we add a classname to the <body> element. This is IE-8 compatible.

This is shorthand for the following..

Performance

If your more concerned with performance over cross-compatibility you can shorten it to the following which is 4% faster.

Convenience

Alternatively you could use jQuery but the resulting performance is significantly slower. 94% slower according to jsPerf

Removing the class

Using jQuery selectively is the best method for removing a class if your concerned with performance

Without jQuery it's 32% slower

  • jsPerf Test Case: Adding a Class
  • jsPerf Test Case: Removing a Class

Using Prototype

davidcondrey's user avatar

  • Wow thanks :) Will the shorthand version ( a.classList ? ... ) have any speed difference compared to the normal one ( if (a.classList) { .... )? –  Wilf Commented Sep 6, 2015 at 12:47
  • 5 There's olso classList.remove() . Why didn't you used it? it's much faster than jQuery jsperf.com/remove-class-vanilla-vs-jquery –  Fez Vrasta Commented Jan 16, 2016 at 16:44
  • @FezVrasta classList isn't supported before IE 10, which still has a decent market share (+13% on netmarketshare.com). –  Adam Commented Mar 18, 2016 at 15:58
  • 6 @Adam he used classList for everything except to remove classes, this is why I'm asking it. –  Fez Vrasta Commented Mar 18, 2016 at 16:02
  • @FezVrasta Under cross compatible I did use .add() but only after checking to see if it is available, hense cross compatible . For remove I did not bother to repeat myself so I did not include as many options. –  davidcondrey Commented Sep 2, 2016 at 10:49

2 different ways to add class using JavaScript

JavaScript provides 2 different ways by which you can add classes to HTML elements:

  • Using element.classList.add() Method
  • Using className property
Using both methods you can add single or multiple classes at once.

1. Using element.classList.add() Method

var element = document.querySelector('.box'); // using add method // adding single class element.classList.add('color'); // adding multiple class element.classList.add('border', 'shadow'); .box { width: 200px; height: 100px; } .color { background: skyblue; } .border { border: 2px solid black; } .shadow { box-shadow: 5px 5px 5px gray; } <div class="box">My Box</div>

2. Using element.className Property

Note : Always use += operator and add a space before class name to add class with classList method.

var element = document.querySelector('.box'); // using className Property // adding single class element.className += ' color'; // adding multiple class // keep classes space separated element.className += ' border shadow'; .box { width: 200px; height: 100px; } .color { background: skyblue; } .border { border: 2px solid black; } .shadow { box-shadow: 5px 5px 5px gray; } <div class="box">My Box</div>

Satish Chandra Gupta's user avatar

  • 1 plus one for adding more than one class. –  Timo Commented May 28, 2022 at 18:53

Another approach to add the class to element using pure JavaScript

For adding class:

For removing class:

Shoaib Chikate's user avatar

  • 5 That's already been answered several times by other users, including discussions of browser support and shims. –  bafromca Commented Sep 23, 2014 at 16:10
  • @bafromca I didn't see that previous answer was given and its my mistake. You can flag this answer –  Shoaib Chikate Commented Sep 24, 2014 at 6:00
  • 4 @ShoaibChikate: you can also delete the answer if you'd like (you'll keep the points). Just trying to reduce clutter on this question; totally up to you. –  Dan Dascalescu Commented Jun 25, 2015 at 8:55

First approach helped in adding the class when second approach didn't work. Don't forget to keep a space in front of the ' someclassname' in the first approach.

For removal you can use:

Athira V Ajit's user avatar

When the work I'm doing doesn't warrant using a library, I use these two functions:

meouw's user avatar

  • 17 if( cn.indexOf( classname ) != -1 ) { return; } Beware that if you add the class “btn” with the class “btn-info” being already here, this fails. –  Alexandre Dieulot Commented Apr 17, 2013 at 21:05
  • 2 you should use element.className.split(" "); to prevent the problem @AlexandreDieulot reported here. –  Amir Forsati Commented Aug 27, 2018 at 8:37

Assuming you're doing more than just adding this one class (eg, you've got asynchronous requests and so on going on as well), I'd recommend a library like Prototype or jQuery .

This will make just about everything you'll need to do (including this) very simple.

So let's say you've got jQuery on your page now, you could use code like this to add a class name to an element (on load, in this case):

Check out the jQuery API browser for other stuff.

rfunduk's user avatar

You can use the classList.add OR classList.remove method to add/remove a class from a element.

The above code will add(and NOT replace) a class "anyclass" to nameElem. Similarly you can use classList.remove() method to remove a class.

sjv's user avatar

  • very nice, but not supported in IE <= 9 or Safari <=5.0 ... :( ( caniuse.com/classlist ) –  simon Commented Sep 16, 2013 at 4:46
  • 1 This has already been discussed , including browser support. –  Dan Dascalescu Commented Jun 25, 2015 at 8:57

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:

To change all classes for an element:

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

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

Mo.'s user avatar

This might be helpful for WordPress developers etc.

Akalanka Ekanayake's user avatar

If you don't want to use jQuery and want to support older browsers:

Ferran Maylinch's user avatar

I too think that the fastest way is to use Element.prototype.classList as in es5: document.querySelector(".my.super-class").classList.add('new-class') but in ie8 there is no such thing as Element.prototype.classList, anyway you can polyfill it with this snippet (fell free to edit and improve it):

if(Element.prototype.classList === void 0){ function DOMTokenList(classes, self){ typeof classes == "string" && (classes = classes.split(' ')) while(this.length){ Array.prototype.pop.apply(this); } Array.prototype.push.apply(this, classes); this.__self__ = this.__self__ || self } DOMTokenList.prototype.item = function (index){ return this[index]; } DOMTokenList.prototype.contains = function (myClass){ for(var i = this.length - 1; i >= 0 ; i--){ if(this[i] === myClass){ return true; } } return false } DOMTokenList.prototype.add = function (newClass){ if(this.contains(newClass)){ return; } this.__self__.className += (this.__self__.className?" ":"")+newClass; DOMTokenList.call(this, this.__self__.className) } DOMTokenList.prototype.remove = function (oldClass){ if(!this.contains(newClass)){ return; } this[this.indexOf(oldClass)] = undefined this.__self__.className = this.join(' ').replace(/ +/, ' ') DOMTokenList.call(this, this.__self__.className) } DOMTokenList.prototype.toggle = function (aClass){ this[this.contains(aClass)? 'remove' : 'add'](aClass) return this.contains(aClass); } DOMTokenList.prototype.replace = function (oldClass, newClass){ this.contains(oldClass) && this.remove(oldClass) && this.add(newClass) } Object.defineProperty(Element.prototype, 'classList', { get: function() { return new DOMTokenList( this.className, this ); }, enumerable: false }) }

asdru's user avatar

To add, remove or check element classes in a simple way:

Marcos Fernandez Ramos's user avatar

You can use modern approach similar to jQuery

If you need to change only one element, first one that JS will find in DOM, you can use this:

document.querySelector('.someclass').className += " red"; .red { color: red; } <div class="someclass"> <p>This method will add class "red" only to first element in DOM</p> </div> <div class="someclass"> <p>lorem ipsum</p> </div> <div class="someclass"> <p>lorem ipsum</p> </div> <div class="someclass"> <p>lorem ipsum</p> </div>

Keep in mind to leave one space before class name.

If you have multiple classes where you want to add new class, you can use it like this

document.querySelectorAll('.someclass').forEach(function(element) { element.className += " red"; }); .red { color: red; } <div class="someclass"> <p>This method will add class "red" to all elements in DOM that have "someclass" class.</p> </div> <div class="someclass"> <p>lorem ipsum</p> </div> <div class="someclass"> <p>lorem ipsum</p> </div> <div class="someclass"> <p>lorem ipsum</p> </div>

Vladimir Jovanović's user avatar

  • how about to target the last class instead? –  staminna Commented Aug 14, 2020 at 13:35

I know IE9 is shutdown officially and we can achieve it with element.classList as many told above but I just tried to learn how it works without classList with help of many answers above I could learn it.

Below code extends many answers above and improves them by avoiding adding duplicate classes.

Let Me Tink About It's user avatar

Just to elaborate on what others have said, multiple CSS classes are combined in a single string, delimited by spaces. Thus, if you wanted to hard-code it, it would simply look like this:

From there you can easily derive the javascript necessary to add a new class... just append a space followed by the new class to the element's className property. Knowing this, you can also write a function to remove a class later should the need arise.

Misko's user avatar

I think it's better to use pure JavaScript, which we can run on the DOM of the Browser.

Here is the functional way to use it. I have used ES6 but feel free to use ES5 and function expression or function definition, whichever suits your JavaScript StyleGuide.

'use strict' const oldAdd = (element, className) => { let classes = element.className.split(' ') if (classes.indexOf(className) < 0) { classes.push(className) } element.className = classes.join(' ') } const oldRemove = (element, className) => { let classes = element.className.split(' ') const idx = classes.indexOf(className) if (idx > -1) { classes.splice(idx, 1) } element.className = classes.join(' ') } const addClass = (element, className) => { if (element.classList) { element.classList.add(className) } else { oldAdd(element, className) } } const removeClass = (element, className) => { if (element.classList) { element.classList.remove(className) } else { oldRemove(element, className) } }

revelt's user avatar

Sample with pure JS. In first example we get our element's id and add e.g. 2 classes.

In second example we get element's class name and add 1 more.

Vasyl Gutnyk's user avatar

For those using Lodash and wanting to update className string:

s.d's user avatar

The majority of people use a .classList.add on a getElementById , but I i wanted to use it on a getElementByClassName . To do that, i was using a forEach like this :

document.getElementsByClassName("class-name").forEach(element => element.classList.add("new-class"));

But it didn't work because i discovered that getElementsByClassName returns a HTML collection and not an array. To handle that I converted it to an array with this code :

[...document.getElementsByClassName("class-name")].forEach(element => element.classList.add("new-class"));

Soufian's user avatar

image1.parentNode.className+=' box'; .box { width: 100px; height:100px; background: red; } <div class="someclass"> <img ... id="image1" name="image1" /> </div>

Kamil Kiełczewski's user avatar

You can use the API querySelector to select your element and then create a function with the element and the new classname as parameters. Using classlist for modern browsers, else for IE8. Then you can call the function after an event.

Anastasis's user avatar

  • This has already been discussed , along with browser support. –  Dan Dascalescu Commented Jun 25, 2015 at 8:59

In my case, I had more than one class called main-wrapper in the DOM, but I only wanted to affect the parent main-wrapper . Using :first Selector ( https://api.jquery.com/first-selector/ ), I could select the first matched DOM element. This was the solution for me:

I also did the same thing for the second children of a specific div in my DOM as you can see in the code where I used $('#deals-index > div:eq(0) > div:eq(1)').addClass('doubleheaderredesign'); .

NOTE: I used jQuery as you can see.

Jaime Montoya's user avatar

first, give the div an id. Then, call function appendClass:

tehvan's user avatar

  • 1 it will replace the class not append ! Maybe be a line is missing or a oldClass+" "+classToAppend instead of the last classToAppend –  Vinze Commented Feb 3, 2009 at 14:20
  • indexOf is a naive solution and has a problem already pointed out . –  Dan Dascalescu Commented Jun 25, 2015 at 8:58

This js code works for me

provides classname replacement

To add just use

To remove use

Hope this is helpful to sombody

Anon's user avatar

In YUI, if you include yuidom , you can use

YAHOO.util.Dom.addClass('div1','className');

Alagu's user avatar

  • 16 It said JavaScript, not jQuery or YUI. –  Radek Commented May 13, 2013 at 15:07

Not the answer you're looking for? Browse other questions tagged javascript dom-manipulation or ask your own question .

  • The Overflow Blog
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • The hat-check problem
  • If Miles doesn’t consider Peter’s actions as hacking, then what does he think Peter is doing to the computer?
  • How to determine if a set is countable or uncountable?
  • How do I type the characters ├ ─ and └?
  • Incident in WWII re US troops in non-segregated British pubs
  • Which point on a hyperbola is closest to a circle
  • Video game where the hero gets transported to another world with his sister to aid a king in a war
  • Miracle Miracle Octad Generator Generator
  • What is the difference between an `.iso` OS for a network and an `.iso` OS for CD?
  • Vector of integers such that almost all dot products are positive
  • Millennial reign and New Heaven and New Earth
  • Sticker on caption phone says that using the captions can be illegal. Why?
  • Calculate the sum of numbers in a rectangle
  • Is there racial discrimination at Tbilisi airport?
  • Old TV episode about a rich man and his guests trapped in his high-tech underground bunker after a nuclear disaster
  • What (if any) pre-breathes were "attempted" on the ISS, and why?
  • Visualizing histogram of data on unit circle?
  • How can one says that a particle IS a representation of some group?
  • Is it possible to do physics without mathematics?
  • Jacobi two square's theorem last step to conclusion
  • Which Cards Use -5V and -12V in IBM PC Compatible Systems?
  • An integral using Mathematica or otherwise
  • Numbering system of equations and specific lines therein
  • The work-energy theorem in a resistor

assignment through javascript

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

Addition Assignment (+=) Operator in Javascript

JavaScript Addition assignment operator( += ) adds a value to a variable, The Addition Assignment (+ =) Sums up left and right operand values and then assigns the result to the left operand. The two major operations that can be performed using this operator are the addition of numbers and the concatenation of strings.

Example 1: In this example, we will concatenate two numbers as well as two strings by using the Addition Assignment operator(+=)

 

Output: When the operator is used on a number addition is performed and concatenation is performed on strings

Example 2: Here with the help of for..in  loop, we use the Additional assignment operator.

 

Output: Here we use an operator to add filtered content to a string

Supported browser:

  • Google Chrome
  • Mozilla Firefox
  • Internet Explorer

We have a complete list of Javascript Assignment operators, to check those please go through the JavaScript Assignment operators article.

Please Login to comment...

Similar reads.

  • Web Technologies
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Review Our JavaScript Assignment Template

    assignment through javascript

  2. Assignment Operator in JavaScript

    assignment through javascript

  3. Assignment Operators in JavaScript

    assignment through javascript

  4. JavaScript Assignment Operators

    assignment through javascript

  5. JavaScript Assignment Operators

    assignment through javascript

  6. Assignment operators in javascript || Javascript assignment operators

    assignment through javascript

COMMENTS

  1. JavaScript Assignment

    Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  2. Assignment (=)

    The assignment (=) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. ... JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

  3. JavaScript Object.assign() Method

    Description. The Object.assign() method copies properties from one or more source objects to a target object. Object.assign () copies properties from a source object to a target object. Object.create () creates an object from an existing object. Object.fromEntries () creates an object from a list of keys/values.

  4. JavaScript OR (||) variable assignment explanation

    That is, JavaScript "short-circuits" the evaluation of Boolean operators and will return the value associated with either the first non-false variable value or whatever the last variable contains. See Anurag's explanation of those values that will evaluate to false. Using this technique is not good practice for several reasons; however.

  5. Javascript Assignment Operators (with Examples)

    In this tutorial, you will learn about all the different assignment operators in javascript and how to use them in javascript. Assignment Operators. In javascript, there are 16 different assignment operators that are used to assign value to the variable. It is shorthand of other operators which is recommended to use.

  6. The Modern JavaScript Tutorial

    Modern JavaScript Tutorial: simple, but detailed explanations with examples and tasks, including: closures, document and events, object oriented programming and more. EN. AR ... Destructuring assignment. Date and time. JSON methods, toJSON.

  7. Logical AND assignment (&&=)

    Description. Logical AND assignment short-circuits, meaning that x &&= y is equivalent to x && (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not truthy, due to short-circuiting of the logical AND operator. For example, the following does not throw an error, despite x being const:

  8. JavaScript Assignment Operators

    JavaScript Division Assignment Operator in JavaScript is represented by "/=". This operator is used to divide the value of the variable by the value of the right operand and that result is going to be assigned to the variable. This can also be explained as dividing the value of the variable by an expression and assigning that result to the variable

  9. JavaScript Operators (with Examples)

    JavaScript operators are special symbols that perform operations on one or more operands (values). In this tutorial, you will learn about JavaScript operators with the help of examples. ... JavaScript Assignment Operators. We use assignment operators to assign values to variables. For example, let x = 5; Here, we used the = operator to assign ...

  10. Destructuring assignment

    Unpacking values from a regular expression match. When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if ...

  11. Destructuring assignment

    It's called "destructuring assignment," because it "destructurizes" by copying items into variables. However, the array itself is not modified. It's just a shorter way to write: // let [firstName, surname] = arr; let firstName = arr [0]; let surname = arr [1]; Ignore elements using commas.

  12. 40 JavaScript Projects for Beginners

    I have created a list of 40 beginner friendly project tutorials in Vanilla JavaScript, React, and TypeScript. My advice for tutorials would be to watch the video, build the project, break it apart and rebuild it your own way. Experiment with adding new features or using different methods. That will test if you have really learned the concepts ...

  13. JavaScript Exercises

    Learn JavaScript ... Create your own server using Python, PHP, React.js, Node.js, Java, C#, etc. ... Introduction JS Where To JS Output JS Statements JS Syntax JS Comments JS Variables JS Let JS Const JS Operators JS Arithmetic JS Assignment JS Data Types JS Functions JS Objects JS Object Properties JS Object Methods JS Object Display JS Object ...

  14. JavaScript Variables

    All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs.

  15. 2,500+ JavaScript Practice Challenges // Edabit

    How Edabit Works. This is an introduction to how challenges on Edabit work. In the Code tab above you'll see a starter function that looks like this: function hello () { } All you have to do is type return "hello edabit.com" between the curly braces { } and then click the Check button. If you did this correctly, the button will turn red and ...

  16. How do I programmatically set the value of a select box element using

    With plain Javascript, this can also be achieved with two Document methods: With document.querySelector , you can select an element based on a CSS selector: document.querySelector('#leaveCode').value = '14'

  17. JavaScript Tutorial

    JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages. 2. CSS to specify the layout of web pages. 3. JavaScript to program the behavior of web pages. This tutorial covers every version of JavaScript: The Original JavaScript ES1 ES2 ES3 (1997-1999)

  18. Subtraction Assignment ( -=) Operator in Javascript

    We will now see some examples of the javascript Subtraction Assignment (-=). Example 1: In this example, we will use the Subtraction Assignment Operator on numerical values. Javascript. let number = 9; number -= 5; console.log(number); Output: 4. Example 2: In this example, we will be subtracting a string with a number using the subtraction ...

  19. assign tasks

    Select the Assign to check box to convert your comment into a task. Assign the task to the person you tagged by checking the checkbox. Click the green arrow below the comment, or press Ctrl + Enter to post your comment and assign the task. The task has been assigned . Scenarios to try Reassign a task

  20. How do you assign a JavaScript 'onclick' attribute dynamically?

    As the other said you should assign a function. Just wanted to point out that in this case you want to pass a value so you need to assign an anonymous function (or a named function defined inline) like. button.onclick = function() {otherfunction(parameter)}; If the function you want to assign does NOT require a parameter you can use it directly.

  21. South Carolina considers its energy future through state Senate

    COLUMBIA, S.C. (AP) — The South Carolina Senate on Thursday started its homework assignment of coming up with a comprehensive bill to guide energy policy in a rapidly growing state and amid a quickly changing power- generation world. The Special Committee on South Carolina's Energy Future plans several meetings through October.

  22. javascript

    What does adding a class to a DOM element have to do with learning the language? document.getElementById('div1').className is as much a library related issue as using jQuery to do the same is. The question was "how can I do that", a thoroughly tested library is the sensible answer.

  23. Addition Assignment (+=) Operator in Javascript

    JavaScript Addition assignment operator (+=) adds a value to a variable, The Addition Assignment (+ =) Sums up left and right operand values and then assigns the result to the left operand. The two major operations that can be performed using this operator are the addition of numbers and the concatenation of strings. Syntax: a += b.