• 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.

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 ?

Yangshun Tay's user avatar

11 Answers 11

Use element.style :

mikemaccana's user avatar

Just set the style :

Or if you like, you can use jQuery :

djdd87's user avatar

For most styles do this:

For styles that have hyphens in the name do this instead:

Daniel X Moore's user avatar

That's actually quite simple with vanilla JavaScript:

Justin Niessner's user avatar

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:

Mattia Astorino's user avatar

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:

Nick's user avatar

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:

afable's user avatar

if you want to add a global property, you can use:

Hetdev's user avatar

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

Daut's user avatar

Robert Longson's user avatar

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 .

Hot Network Questions

set property javascript

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:

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

set property javascript

Get certified by completing a course today!

Subscribe

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.

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!

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:

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.

Lesson navigation

w3docs logo

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:

w3docs logo

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:

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.

JS Control Flow

JS Functions

JavaScript Objects

JavaScript Getter and Setter

JavaScript for...in loop

Exceptions and Modules

JavaScript Classes

JavaScript Asynchronous

Miscellaneous

Related Topics

JavaScript Methods and this Keyword

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 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:

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.

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.

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.

Table of Contents

Sorry about that.

Related Tutorials

JavaScript Tutorial

setProperty method

Parameters:

Return value:, example html code 1:, example html code 2:, supported by objects:, related pages:, external links:, post content.

IMAGES

  1. 38 Javascript Readonly Class Property

    set property javascript

  2. Javascript Define Property Get Set

    set property javascript

  3. 46 Javascript Get Property Value

    set property javascript

  4. Practical use case for Javascript Function Properties (ReactJS)

    set property javascript

  5. Set in JavaScript

    set property javascript

  6. How to set background-image property from JavaScript

    set property javascript

VIDEO

  1. JavaScript HTML DOM Collections

  2. Auto Change Text Color Animation using Html And CSS

  3. setInterval In JavaScript Explained

  4. 08

  5. How To Sum Two Object Property Values In Javascript || Javascript || Javascript Tutorial || Course

  6. CSS Shorthands #The Beginner’s Guide to CSS Shorthand #webdevelopment #css

COMMENTS

  1. Set

    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.

  2. setter

    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

  3. JavaScript Properties

    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

  4. Set CSS property in JavaScript?

    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');

  5. HTML DOM Element setAttribute() Method

    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

  6. Property getters and setters

    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:

  7. JavaScript Property 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: 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 } };

  8. JSObject.SetProperty Method (System.Runtime.InteropServices.JavaScript

    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.

  9. JavaScript Getter and Setter (with Examples)

    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.

  10. setProperty method JavaScript

    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 ...