- Skip to main content
- Skip to search
- Skip to select language
- Get MDN Plus
- English (US)
The set syntax binds an object property to a function to be called when there is an attempt to set that property. It can also be used in classes .
There are some additional syntax restrictions:
- A setter must have exactly one parameter.
The name of the property to bind to the given function. In the same way as other properties in object initializers , it can be a string literal, a number literal, or an identifier.
An alias for the variable that holds the value attempted to be assigned to prop .
You can also use expressions for a computed property name to bind to the given function.

Description
In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.
Defining a setter on new objects in object initializers
The following example define a pseudo-property current of object language . When current is assigned a value, it updates log with that value:
Note that current is not defined, and any attempts to access it will result in undefined .
Using setters in classes
You can use the exact same syntax to define public instance setters that are available on class instances. In classes, you don't need the comma separator between methods.
Setter properties are defined on the prototype property of the class and are thus shared by all instances of the class. Unlike setter properties in object literals, setter properties in classes are not enumerable.
Static setters and private setters use similar syntaxes, which are described in the static and private class features pages.
Removing a setter with the delete operator
If you want to remove the setter, you can just delete it:
Defining a setter on existing objects using defineProperty
To append a setter to an existing object, use Object.defineProperty() .
Using a computed property name
Specifications, browser compatibility.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- Object.defineProperty()
- __defineGetter__
- __defineSetter__
- Defining getters and setters in JavaScript Guide
- Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
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.
Set CSS property in JavaScript?
I've created the following...
How would I now set CSS attributes e.g width: 100px ?
11 Answers 11
Use element.style :
- 20 What about for the unofficial ones like -webkit-background-size ? Is there a way to set these with plain js or do we have to use jQuery? – Luke Jul 24, 2013 at 0:41
- 73 @Luke obj.style["-webkit-background-size"] = "400px" – Daniel X Moore Oct 28, 2013 at 23:23
- This actually styles the element in the element and not in the stylesheet. – JΛYDΞV Jan 17, 2020 at 14:23
Just set the style :
Or if you like, you can use jQuery :

- 5 @Sime - My quotes aren't inconsistent. I always use double quotes for JS as that's the standard at work. Anyway, the first line had single quotes as I copied it from the OPs question. Corrected now anyway. – djdd87 Mar 4, 2011 at 15:04
- 1 Well, they're OK now, but they were inconsistent at the time of my comment :) – Šime Vidas Mar 4, 2011 at 15:07
- 2 @Sime - I did acknoledge that: "Anyway, the first line had single quotes as I copied it from the OPs question. Corrected now anyway." – djdd87 Mar 4, 2011 at 15:08
For most styles do this:
For styles that have hyphens in the name do this instead:
That's actually quite simple with vanilla JavaScript:
Just for people who want to do the same thing in 2018
You can assign a CSS custom property to your element (through CSS or JS) and change it:
Assigment through CSS:
Assignment through JS
Get property value through JS
Here useful links:
- https://developer.mozilla.org/en-US/docs/Web/CSS/-- *
- https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue
- https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty
- https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/removeProperty
All of the answers tell you correctly how to do what you asked but I would advise using JavaScript to set a class on the element and style it by using CSS. That way you are keeping the correct separation between behaviour and style.
Imagine if you got a designer in to re-style the site... they should be able to work purely in CSS without having to work with your JavaScript.
In prototype I would do:
- 1 +1 from me - much easier / cleaner to keep all your CSS separate. – Ian Oxley Mar 4, 2011 at 15:29
- 1 jQuery version of this for reference... $(selector).addClass('blah') – zgr024 Jun 5, 2013 at 4:14
- Vanilla version: newElement.classList.add('blah') – rodorgas Jun 16, 2021 at 13:04
When debugging, I like to be able to add a bunch of css attributes in one line:
Getting used to this style you can add a bunch of css in one line like so:

if you want to add a global property, you can use:
This works well with most CSS properties if there are no hyphens in them.
For properties with hyphens in them like max-width , you should convert the sausage-case to camelCase

- "sausage-case" is nice but I like "kebab-case" better :) – user9645 Dec 16, 2021 at 15:42
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged javascript css or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- NBA G League free throw
- Question about Nyquist sampling - filtering of high image copies
- Forced to pay a customs fee for importing a used wedding dress into the Netherlands. Is there a way to avoid paying?
- What video game is Charlie playing in Poker Face S01E07?
- Loose bottom bracket on MTB
- What is the purpose of non-series Shimano components?
- How do/should administrators estimate the cost of producing an online introductory mathematics class?
- How should I go about getting parts for this bike?
- Why are all monasteries human?
- Blender python - set location does not use centimeters
- Difference between "select-editor" and "update-alternatives --config editor"
- Are demand and time deposit accounts really loans _to_ the bank?
- How to measure the power in mW of a radio signal
- get unique without sorting in jq
- How or would these mechanical wings work?
- How can I check before my flight that the cloud separation requirements in VFR flight rules are met?
- Create a structure to store student data and display all the records in the array
- Example of trickiness of finite lattice representation problem?
- High-side gate driver application schematic
- Will DL360 Gen 8 servers fit in rails designed for DL360 Gen 7 servers?
- double quotes not working in IEEEtran
- Minimising the environmental effects of my dyson brain
- Google maps for Space exploration
- A plastic tab/tag stuck out of the GE dryer drum gap. Does anyone know what it is, if it is a part of the dryer, and if so how I can fix it?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
JS Reference
Html events, html objects, other references, html dom element setattribute().
Add a class attribute to an element:
The Element Object
More examples below.
Definition and Usage
The setAttribute() method sets a new value to an attribute.
If the attribute does not exist, it is created first.
The getAttribute() Method
The removeAttribute() Method
The hasAttribute() Method
The hasAttributes() Method
The getAttributeNode() method
The setAttributeNode() method
The removeAttributeNode() method
HTML Attributes
Return Value
It is possible to add a style attribute with a value to an element, but it is not recommended because it can overwrite other properties in the style attribute.
Use Properties of the Style Object instead:
Advertisement
More Examples
Change an input field to an input button:
Add a href attribute to an <a> element:
Change the value of the target attribute to "_self":
Browser Support
element.setAttribute() is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
- FR Français
- ID Indonesia
- IT Italiano
- UK Українська
We want to make this open-source project available for people all around the world.
Help to translate the content of this tutorial to your language!
- The JavaScript language
- Object properties configuration
Property getters and setters
There are two kinds of object properties.
The first kind is data properties . We already know how to work with them. All properties that we’ve been using until now were data properties.
The second type of property is something new. It’s an accessor property . They are essentially functions that execute on getting and setting a value, but look like regular properties to an external code.

Getters and setters
Accessor properties are represented by “getter” and “setter” methods. In an object literal they are denoted by get and set :
The getter works when obj.propName is read, the setter – when it is assigned.
For instance, we have a user object with name and surname :
Now we want to add a fullName property, that should be "John Smith" . Of course, we don’t want to copy-paste existing information, so we can implement it as an accessor:
From the outside, an accessor property looks like a regular one. That’s the idea of accessor properties. We don’t call user.fullName as a function, we read it normally: the getter runs behind the scenes.
As of now, fullName has only a getter. If we attempt to assign user.fullName= , there will be an error:
Let’s fix it by adding a setter for user.fullName :
As the result, we have a “virtual” property fullName . It is readable and writable.
Accessor descriptors
Descriptors for accessor properties are different from those for data properties.
For accessor properties, there is no value or writable , but instead there are get and set functions.
That is, an accessor descriptor may have:
- get – a function without arguments, that works when a property is read,
- set – a function with one argument, that is called when the property is set,
- enumerable – same as for data properties,
- configurable – same as for data properties.
For instance, to create an accessor fullName with defineProperty , we can pass a descriptor with get and set :
Please note that a property can be either an accessor (has get/set methods) or a data property (has a value ), not both.
If we try to supply both get and value in the same descriptor, there will be an error:
Smarter getters/setters
Getters/setters can be used as wrappers over “real” property values to gain more control over operations with them.
For instance, if we want to forbid too short names for user , we can have a setter name and keep the value in a separate property _name :
So, the name is stored in _name property, and the access is done via getter and setter.
Technically, external code is able to access the name directly by using user._name . But there is a widely known convention that properties starting with an underscore "_" are internal and should not be touched from outside the object.
Using for compatibility
One of the great uses of accessors is that they allow to take control over a “regular” data property at any moment by replacing it with a getter and a setter and tweak its behavior.
Imagine we started implementing user objects using data properties name and age :
…But sooner or later, things may change. Instead of age we may decide to store birthday , because it’s more precise and convenient:
Now what to do with the old code that still uses age property?
We can try to find all such places and fix them, but that takes time and can be hard to do if that code is used by many other people. And besides, age is a nice thing to have in user , right?
Let’s keep it.
Adding a getter for age solves the problem:
Now the old code works too and we’ve got a nice additional property.
- If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
- If you can't understand something in the article – please elaborate.
- To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)
Lesson navigation
- © 2007—2023 Ilya Kantor
- about the project
- terms of usage
- privacy policy

JavaScript Property Getters and Setters
In this chapter, we cover the types of object properties.
As a rule, there exist two object property types: data properties and accessor properties. All the properties we represented before are data properties. Accessor properties are relatively new and execute on getting and setting values. However, they seem like a regular property to the external code.
The Usage of Getters and Setters
The so-called getter and setter methods represent accessor properties. They are specified by get and set inside an object literal as shown below:
The getter will operate once obj.propName is read. The setter will work once it is already assigned.
An example of a user object with a name and a surname is demonstrated below:

The next step is adding a fullName property (it should be "W3Docs Javscsript" ). To avoid copy-pasting the existing information, it can be implemented as an accessor like this:
As it was told, an accessor property can look like a regular one. That’s its main idea.
The site.fullName is not called as a function. It is read normally, and the getter is performed behind the scenes.
The attempt to assign user.fullName= will lead to an error like here:
Adding a setter for site.fullName will help to fix it:
The result will be having a virtual fullName property, which is both writable and readable.
About Accessor Descriptors
Now, let’s check out the descriptors for accessor properties. They are different from the descriptors for the data properties. There isn’t any value or writable for accessor properties. Instead, they include get and set functions.
An accessor descriptor may include:
- get – a no-argument function, operating once a property is read,
- set – a function that has a single argument, which is called once the property is set,
- enumerable – the same as for data properties,
- configurable – the same as for data properties.
For generating a fullName accessor with defineProperty , a descriptor with get and set should be passed like this:
An important note: a property must either be an accessor property or a data property.
Trying to put both in the same descriptor will lead to an error like this:
Wider Usage of Getters and Setters
Getters and setters can be usefully performed as wrappers over property values for gaining more control over operations.
For prohibiting very short names for the user, you may have a setter name, storing the value within a separate property _name like this:
So, the name is kept in the _name property. The access is implemented through getter and setter.
The Usage for Compatibility
Another significant use of accessors is that they allow controlling a regular data property at any moment by interchanging it with a getter and setter. Here is an example of user objects, applying name and age data properties:
Now, the main issue is how to deal with the old code, which still applies the age property.
The most efficient way of solving the issue is to add a getter for the age property:
So, finally, both the code works, and there is an additional useful property.
Learn coding interactively.
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
Related Topics
- Javascript Object.defineProperty()
JavaScript Methods and this Keyword
- Javascript Object.preventExtensions()
In this tutorial, you will learn about JavaScript getter and setter methods with the help of examples.
In JavaScript, there are two kinds of object properties:
- Data properties
- Accessor properties
Data Property
Here's an example of data property that we have been using in the previous tutorials.
Accessor Property
In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use these two keywords:
- get - to define a getter method to get the property value
- set - to define a setter method to set the property value
- JavaScript Getter
In JavaScript, getter methods are used to access the properties of an object. For example,
In the above program, a getter method getName() is created to access the property of an object.
Note: To create a getter method, the get keyword is used.
And also when accessing the value, we access the value as a property.
When you try to access the value as a method, an error occurs.
- JavaScript Setter
In JavaScript, setter methods are used to change the values of an object. For example,
In the above example, the setter method is used to change the value of an object.
Note: To create a setter method, the set keyword is used.
As shown in the above program, the value of firstName is Monica .
Then the value is changed to Sarah .
Note : Setter must have exactly one formal parameter.
- JavaScript Object.defineProperty()
In JavaScript, you can also use Object.defineProperty() method to add getters and setters. For example,
In the above example, Object.defineProperty() is used to access and change the property of an object.
The syntax for using Object.defineProperty() is:
The Object.defineProperty() method takes three arguments.
- The first argument is the objectName.
- The second argument is the name of the property.
- The third argument is an object that describes the property.
Table of Contents
- Introduction
Sorry about that.
Related Tutorials
JavaScript Tutorial
setProperty method
- To get the value of a style property, use the getPropertyValue and getAttribute methods.
- To remove a style property, use the removeProperty and removeAttribute methods.
Parameters:
Return value:, example html code 1:, example html code 2:, supported by objects:, related pages:, external links:, post content.

IMAGES
VIDEO
COMMENTS
Set The Set object lets you store unique values of any type, whether primitive values or object references. Description Set objects are collections of values. A value in the Set may only occur once; it is unique in the Set 's collection. You can iterate through the elements of a set in insertion order.
In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value. Examples
A JavaScript object is a collection of unordered properties. Properties can usually be changed, added, and deleted, but some are read only. Accessing JavaScript Properties The syntax for accessing the property of an object is: objectName.property // person.age or objectName [ "property" ] // person ["age"] or
You can assign a CSS custom property to your element (through CSS or JS) and change it: Assigment through CSS: element { --element-width: 300px; width: var (--element-width, 100%); } Assignment through JS ELEMENT.style.setProperty ('--element-width', NEW_VALUE); Get property value through JS ELEMENT.style.getPropertyValue ('--element-width');
It is possible to add a style attribute with a value to an element, but it is not recommended because it can overwrite other properties in the style attribute. Use Properties of the Style Object instead: NO: element.setAttribute("style", "background-color:red;"); YES: element.style.backgroundColor = "red"; More Examples
set - a function with one argument, that is called when the property is set, enumerable - same as for data properties, configurable - same as for data properties. For instance, to create an accessor fullName with defineProperty, we can pass a descriptor with get and set:
The so-called getter and setter methods represent accessor properties. They are specified by get and set inside an object literal as shown below: let obj = { get propName () { // getter, the code executed when obj.propName id getting }, set propName (value) { // setter, the code executed when obj.propName = value is setting } };
SetProperty (String, Int32) Defines a new property on the target object, or modifies an existing property to have the specified value. C#. public void SetProperty (string propertyName, int value); Parameters. propertyName. String. The name of the property.
In JavaScript, you can also use Object.defineProperty () method to add getters and setters. For example, In the above example, Object.defineProperty () is used to access and change the property of an object. The Object.defineProperty () method takes three arguments. The first argument is the objectName.
setProperty. method. Adds a property with the specified name and value to the current style object. Note: The setProperty method is supported in Internet Explorer from version 9. If a property with the same name exists on the current style object, then it modifies its value. In older Internet Explorer versions (and in newer ones as well), the ...