This lesson is about reading and changing element attributes in jQuery.

Attributes are a name/value pair that is assigned to elements in a tag. Attribute examples ( href, title, src, class):

Here is the summary text

  • attr() for reading, adding and changing attributes
  • removeAttr() to remove attributes

This lesson deals with the attr() and removeAttr() methods.

To work with CSS classes, there are special jQuery methods, which are described in another lesson . When working on a project in jQuery, you often have to manipulate CSS classes, and class attribute may contain several class names, which makes it much more difficult to work with than other attributes.

If you're going to work with input field values, it's better to use the val() method, which not only provides a simplified version of the value attribute, but can also read and set the values ​​in the selected elements of the select list.

Reading the value of an attribute

Reading the value of an element attribute is simple. All you have to do is call the attr() method on the jQuery object that contains the element, passing it the attribute name to read. The method returns the value of the attribute:

// Display the value of the "href" attribute of the #myLink element alert ($("a#myLink").attr("href"));

If your jQuery object contains multiple elements, the attr() method only reads the attribute values ​​for the first element in the set.

Setting attribute values

The attr() method can also be used to add or change attribute values:

  • If attribute does not exist in the element, it will added and it will be assigned the given value.
  • If attribute already exists, its value will be updated set value.

There are three ways to use the attr() method to add or change attributes:

  1. You can add/change attributes for any element (or set of elements).
  2. You can add/change multiple attributes at once for an element (or elements) by specifying a map of attribute names and values.
  3. it is possible to dynamically add/change a single attribute for multiple elements using a callback function.

Set one attribute

To set or change an attribute of an element, call the attr() method with the attribute name and value. For example:

// Change the value of the "href" attribute of the #myLink element to "http://www.example.com/" // (if the "href" attribute does not exist, it will be created automatically) $("a#myLink"). attr("href", "http://www.example.com/");

It is also possible to set the same attribute on multiple elements:

Setting multiple attributes using a map

You can set multiple attributes at the same time on one or more elements using a map. It's a list of name/value pairs that looks like this:

( name1: value1, name2: value2, ... )

The following example sets two attributes on the img element at the same time:

// Set the "src" and "alt" attributes for the img element #myPhoto $("img#myPhoto").attr(( "src": "mypic.jpg", "alt": "My Photo" ));

You can also set attributes on multiple elements:

// Set "src" and "alt" attributes for all img elements $("img").attr(( "src": "mypic.jpg", "alt": "My Photo" ));

Setting attributes using callback function

Instead of passing attribute values ​​to the attr() method, you can pass the name of the callback function. This way you can dynamically set attribute values ​​for multiple elements according to the element's position, an existing attribute value, or other properties.

The return function must take two arguments:

  • Index of the position of the currently selected element in the set (zero-based)
  • the old attribute value for the currently selected element

The return value of the function is used to replace the value of the attribute.

In addition to the current position of the element and the old value of the attribute, your function can access the element itself using the this keyword. This way you can access any property or method of an element from a callback function.

The example uses a callback to add an alt attribute to each image on the page based on the image's position and its src attribute:

After executing the code, the first image will have an alt attribute with the value "Picture 1: myphoto.jpg" , and the second image will have an alt attribute with the value "Picture 2: yourphoto.jpg" .

Deleting an attribute

To remove an attribute from an element, call the removeAttr() method, passing it the name of the attribute to remove. For example:

// Remove the "title" attribute from the #myLink element $("a#myLink").removeAttr("title");

You can also call the removeAttr() method on a jQuery object that contains multiple elements. The removeAttr() method will remove the given attribute from all elements:

// Remove the "title" attribute from all links $("a").removeAttr("title");

Summary

In this tutorial, we covered the issues of working with element attributes in jQuery:

  • Reading Attribute Values
  • Setting one attribute
  • Setting multiple different attributes at the same time
  • Using a callback function to dynamically set attribute values ​​in a set of elements
  • Removing attributes from an element

The lesson will cover the beginning of the topic: the document object model (javaScript DOM) - the basis of dynamic HTML, access methods to objects will be studied and ways of handling javascript events will be considered

  • Generally an object is a composite data type that combines many values ​​into a common module and allows you to save and retrieve values ​​on request by their names.
  • Earlier, we already started to get acquainted with the concept in javascript.

  • In javascript there is such a thing as DOM - Document Object Model- object model of a web page (html page).
  • Document tags or, as they say, document nodes are its objects.

Let's look at the diagram object hierarchy in JavaScript, and where in the hierarchy the document object in question is located.

The script element has attributes:

  • defer (wait for the page to fully load).
  • Example:

    Properties and attributes of the document object in javaScript

    The document object represents a web page.

    Important: To access the properties and methods of an object in JavaScript, as with other objects, dot notation is used:

    those. the object itself is written first, then its property, attribute or method is indicated with a dot and without spaces

    object.property object.attribute object.method()

    Consider an example:

    Example: let the html document have a tag

    My element

    and specific to him css style(even two styles, the second is useful for the assignment):

    Necessary:

    1. set a new object property, assign a value to it, and output that value;
    2. display the value of an object attribute;
    3. change the value of an attribute of an object.

    Let's do the task in order:
    ✍ Solution:

      Since it javascript language, then the object can be invented and set any property with any value. But first, let's get access to the object (access to the object will be discussed in detail later in this lesson):

      // get access to the object by its id var element = document.getElementById("MyElem"); element.myProperty = 5; // assign property alert(element.myProperty); // display in the dialog box

      The next task is related to the object attribute. Object attribute are tag attributes. Those. in our case there are two of them: the class attribute with the value small and the id attribute. We will work with the class attribute.

      Now let's add some javascript code to display the value of our object's attribute. The code must be after main tags:

      // get access to the object by its id var element = document.getElementById("MyElem"); alert(element.getAttribute("class")); // display in the dialog box

      And the last task: change the value of the attribute. For this we have prepared a style big. Change the value of the class attribute to this style:

      // get access to the object by its id var element = document.getElementById("MyElem"); element.setAttribute("class","big");

      As a result, our element will become larger and turn blue (class big).

    Now let's take a closer look at the methods used in the example for working with attributes.

    Methods for Manipulating Attributes in JavaScript

    Attributes can be added, removed and changed. There are special methods for this:

    • Adding an attribute (setting a new value for it):
    • getAttribute(attr)

    • Checking for the presence of this attribute:
    • removeAttribute(attr)

    Different ways to work with attributes

    Example: Print the value of the text block's value attribute.


    ✍ Solution:
    • Let there be a text block:
    • varelem = document.getElementById("MyElem"); var x = "value";

    • Consider several ways to get the value of an attribute (for output, use alert method()):
    • elem.getAttribute("value" )

      elem.getAttribute("value")

      2. dot notation:

      elem.attributes .value

      elem.attributes.value

      3. bracket notation:


      Set attribute values You can also do it in several ways:

      var x = "key"; // key - attribute name, val - attribute value // 1. elem.setAttribute("key", "val") // 2. elem.attributes.key = "val" // 3. elem.attributes[" key"] = "val" // 4. elem.setAttribute(x, "val")

      body element properties

      Through the document object, you can access the body of the document - the body tag - with some of its useful properties.

      For example, the body tag has two properties: client window width and height:

      document.body.clientHeight - client window height
      document.body.clientWidth - width of the client window


      But the most important thing, as we have already learned, is that through the document object, through special methods, all page elements, that is, tags, are accessed.

      Important: When accessing page tags like this, the script must be at the end of the element tree, before the closing body ! Since by the time the script is executed, all elements should already be “drawn” by the browser on the screen

      Job js8_1. Print a message about the size of the browser window: for example, "browser window dimensions 600 x 400"

      Accessing document elements in javaScript

      There are several options for accessing objects or searching for objects:

    1. Search by id(or getElementById method), returns a specific element
    2. Search by tag name(or the getElementsByTagName method), returns an array of elements
    3. Search by name attribute(or the getElementsByName method), returns an array of elements
    4. Through parent elements(getting all descendants)

    Let's consider each of the options in more detail.

    1. Accessing an element through its id attribute
    2. Syntax: document.getElementById(id)

      The getElementById() method returns the element itself, which can then be used to access data

      Example: The page has a text field with the attribute id="cake" :

      ...

      Necessary


      ✍ Solution:

      alert(document.getElementById("cake").value); // returns "number of cakes"

      You can do the same by implementing an object call through a variable:

      var a=document.getElementById("cake"); alert(a.value); // output the value of the value attribute, i.e. text "number of cakes"

    Important: The script must be placed after the tag!

  • Accessing an array of elements through the name tag name and through the array index
  • Syntax:
    document.getElementsByTagName(name);

    Example: The page has a text field (input tag) with a value attribute:

    ...

    Necessary: print the value of its value attribute


    The getElementsByTagName method organizes access to all input elements through a variable (i.e. to an array of elements input), even if this element is the only one on the page. To refer to a specific element, for example, to the first one, we specify its index (the array starts from zero index).

    ✍ Solution:

      Referring to a specific element by index:

      var a =document.getElementsByTagName("input"); alert(a.value); // returns "number of cakes"

  • Accessing an array of elements by the value of the name attribute
  • Syntax:
    document.getElementsByName(name);

    The getElementsByName("...") method returns array of objects, whose name attribute is equal to the value specified as a method parameter. If there is only one such element on the page, then the method still returns an array (with only one single element).


    Example: Let's say there is an element in the document:

    var element = document.getElementsByName("MyElem"); alert(element.value);

    AT this example there is only one element, but the reference is to the zero element of the array.

    Important: The method works only with those elements for which the name attribute is explicitly provided in the specification: these are the form , input , a , select , textarea tags and a number of other rarer tags.

    The document.getElementsByName method will not work on other elements like div , p , etc.

  • Accessing the children of the parent element
  • Accessing children in javascript happens through the childNodes property. The property belongs to the parent object.

    document.getElementById (parent) .childNodes ;

    document.getElementById(parent).childNodes;

    Consider an example where image tags are wrapped in a container, a div tag. Thus, the div tag is the parent of these images, and the img tags themselves, respectively, are children of the div tag:

    <div id = "div_for_img" > <img src="pic1.jpg" /> <img src="pic2.jpg" /> <img src="pic3.jpg" /> <img src="pic4.jpg" /> </div>

    Now let's output to modal window array element values ​​with descendants, i.e. img tags:

    var myDiv=document.getElementById("div_for_img"); // access parent container var childMas=myDiv.childNodes; // array of children for (var i =0; i< childMas.length;i++){ alert(childMas[i].src); }

    Note that it is convenient to use a loop to iterate over the elements of an array of children. Those. in our example, we get a cycle:

    ... for (var a in childMas) ( alert(childMas[ a] .src ) ; )

    For (var a in childMas)( alert(childMas[a].src); )

  • Other Ways to Access Elements
  • Consider other ways For example:

    <body > <formname="f"> <input type="text" id="t"> <input type = "button" id = "b" value = "(!LANG:button" > !} <select id="s" name="ss"> <option id = "o1" > 1</option> <option id = "o2" > 3</option> <option id = "o3" > 4</option> </select> </form>

    Access:

    ... // unwanted and obsolete element accessors: alert(document.forms [ 0 ] .name ) ; // f alert(document.forms [ 0 ] .elements [ 0 ] .type ) ; // text alert(document.forms [ 0 ] .elements [ 2 ] .options [ 1 ] .id ) ; // o2 alert(document.f .b .type ) ; // button alert(document.f .s .name ) ; // ss alert(document.f .s .options [ 1 ] .id ) ; // o2 // preferred element accessors alert(document.getElementById("t" ) .type ) ; // text alert(document.getElementById("s" ) .name ) ; // ss alert(document.getElementById ("s" ) .options [ 1 ] .id ) ; // 02 alert(document.getElementById("o3" ) .text ) ; // four ...

    ... // unwanted and obsolete element accessors: alert(document.forms.name); // f alert(document.forms.elements.type); // text alert(document.forms.elements.options.id); // o2 alert(document.f.b.type); // button alert(document.f.s.name); // ss alert(document.f.s.options.id); // o2 // preferred element accessors alert(document.getElementById("t").type); // text alert(document.getElementById("s").name); // ss alert(document.getElementById("s").options.id); // 02 alert(document.getElementById("o3").text); // four ...

    Example: Create a button and a text field in an html document. Using a script, colorize the button background (the style.backgroundColor property of the button) and display an inscription "Hi!" in the text field (value attribute).

    Html code:

    document.getElementById("t1").value = "(!LANG:Hello!"; document.getElementById("b1").style.backgroundColor = "red";!}

    Option 2:

    document.getElementById ("t1" ) .setAttribute ("value" , ​​"Hi!" ) ; document.getElementById("b1" ) .style .backgroundColor = "red" ;

    document.getElementById("t1").setAttribute("value","Hello!"); document.getElementById("b1").style.backgroundColor = "red";

    Task Js8_2. Create text field tags according to the image in the figure. Give them the appropriate (shown in the figure) id attribute values. Using the script, add the value " 0 " to all numeric fields (assuming numerical values)

    Checking the correctness of entering form data

    Is the field left empty?

    User-supplied data cannot be trusted. It is unreasonable to assume that users will check them when entering data. So you need to use javascript for this.

    In order to check is the text field empty(for example, after the user fills in the data of a questionnaire), you should refer to the value property. If the property value is an empty string (""), then you need to somehow notify the user about this.


    if(document.getElementById("name").value=="") ( some action, for example, displaying a message with the requirement to fill in the field );

    In addition, you can do without a script. Tag text input fields have a pattern attribute. as its value is indicated regular expression to validate the data in the given form text field. If the attribute is present pattern, then the form will not submit until that text field is filled in correctly.
    For example, to check if a field is left empty:

    Text instead of a numeric value: the isNaN function

    If the field is entering a numeric value, and instead the user enters text, it is necessary to use the isNaN function (from English. "Is it not a number?") that checks the type of the input and returns true if the input is text instead of numeric.

    That. if true is returned, then the user should be prompted to enter the correct format, i.e. number.

    if(isNaN(document.getElementById("minutes").value))( Alert prompting you to enter numeric data );

    Given a page with elements to fill out:


    Fragment html code:

    1 2 3 4 5 6 7 8 9 10 11 12 <form > Name:<input type="text" id="name">
    Number of donuts:<input type="text" id="donuts" >
    Minutes:<input type="text" id="minutes">
    Subtotal:<input type="text" id="subitog" >
    Tax:<input type="text" id="tax">
    Outcome:<input type="text" id="total">
    <input type = "submit" value = "(!LANG:submit" onclick = "placeOrder();" > !} </form> <script type="text/javascript"> ... </script>

    Name:
    Number of donuts:
    Minutes:
    Subtotal:
    Tax:
    Outcome:

    Necessary:
    Fill in the blanks in the code snippet below that checks that two text fields are filled in correctly: name(id="name") and minutes(id="minutes"). Use a check for leaving the field empty ("") and the correct format for filling in the numeric field (isNaN).

    * Do the job also with the pattern attribute of the text fields using .

    Script snippet:

    Used in code to build difficult conditions passed earlier.

    A new concept for you is calling a function as a button event handler:
    onclick="placeOrder();"
    When the button is clicked, the placeOrder() function will be called.

    In this article, we will get acquainted with DOM properties and attributes, consider how they differ and how to work with them correctly. Let's see what methods JavaScript has for performing operations on attributes.

    How is an attribute different from a DOM property?

    Attributes are HTML entities with which we can add certain data to elements in the HTML code.

    When a browser requests a page, it receives its source HTML code. After that, it parses this code and builds a DOM based on it. During this process HTML element attributes are translated into their respective DOM properties.

    For example, the browser, when reading the following HTML line of code, will create the following DOM properties for this element: id , className , src , and alt .

    These properties are accessed in JavaScript code as properties of the object. The object here is a DOM node (element).

    An example where we get the values ​​of the DOM properties for the element above and print their values ​​to the console:

    // get the element var brandImg = document.querySelector("#brand"); // display the values ​​of the element's DOM properties console.log(brandImg.id); // "brand" console.log(brandImg.className); // "brand" console.log(brandImg.src); // "/logo.svg?2" console.log(brandImg.alt); // "site logo"

    Some DOM property names do not match attribute names. One of these is the class attribute. This attribute corresponds to the DOM property className . This difference is due to the fact that the class is keyword in JavaScript, it is reserved and cannot be used. Because of this, the developers of the standard decided to use some other name to match, which was chosen as className .

    Another nuance is related to the fact that the translation of HTML attributes specified in source code document, DOM properties are not always implemented one-to-one.

    If an element has a non-standard HTML attribute, then no property corresponding to it in the DOM is created.

    Another difference is that the values ​​of certain HTML attributes and their corresponding DOM properties can be different. Those. an attribute can have one value, and a DOM property created from it can have another value.

    One such attribute is checked .

    The value of the checked HTML attribute in this case is the empty string. But, the property corresponding to this attribute in the DOM will be set to true . Because according to the rules of the standard, to set true, it is enough just to mention this attribute in the HTML code, and it does not matter what value it will have.

    In this case, even if we do not specify the checked attribute in the HTML code for the input element with the checkbox type, then the checked property will still be created for it in the DOM, but it will be equal to false .

    In addition, JavaScript also allows you to work with attributes. There are special methods in the DOM API for this. But it is advisable to use them only when you really need to work with data in this way.

    In this case, you need to know that when we change the DOM property of an element, the attribute corresponding to it also changes, and vice versa. But this process in browsers is not always performed one to one.

    The main differences between DOM properties and attributes are:

    • the value of an attribute is always a string, and the value of a DOM property is a particular data type (not necessarily a string);
    • the attribute name is case insensitive, and DOM properties are case sensitive. Those. in the HTML code, we can, for example, write the HTML attribute id as Id , ID , etc. The same applies to the attribute name, which we specify in special JavaScript methods to work with him. But we can access the corresponding DOM property only by id and nothing else.

    Working with an element's DOM properties

    Working with the properties of elements in JavaScript, as noted above, is carried out as with the properties of objects.

    But in order to refer to the property of some element, it must first be obtained. You can get a DOM element in JavaScript, for example, using the generic querySelector method, and a collection of DOM elements, for example, using querySelectorAll .

    As a first example, consider the following HTML element:

    Message text...

    On the basis of it, we will analyze how DOM properties are obtained, changed, and new ones are added.

    Reading DOM property values:

    // get the DOM value of the id property var alertId = alert.id; // "alert" // get the value of the DOM property className var alertClass = alert. className; // "alert alert-info" // get the DOM value of the title property var alertId = alert. title; // "Hint text..."

    Changing DOM property values:

    // to change the value of a DOM property, you just need to assign a new value to it alert.title = "(!LANG:New tooltip text"; // присвоим DOM-свойству title элемента новое значение // или так (т.к. обращение к этому свойству мы уже сохранили в переменную alertId) alertId = "Новый текст подсказки"; // или так (т.к. обращение к этому свойству мы уже сохранили в переменную alertId) alert.className = "alert alert-warning"; !}

    Adding DOM properties:

    Alert.lang = "ru"; // set the lang property to "ru" alert.dir = "ltr"; // set the dir property to "ltr"

    An example in which we output to the console all the class values ​​that p elements have on the page:

    Var paragraphs = document.querySelectorAll("p"); for (var i = 0, length = paragraphs. length ; i< length; i++) { if (paragraphs[i].className) { console.log(paragraphs[i].className); }

    An example in which we set the lang property of all elements with the content class to "ru":

    Var contents = document.querySelectorAll(".content"); for (var i = 0, length = contents.length; i< length; i++) { contents[i].lang = "ru"; }

    Element attributes and methods for working with them

    Attributes are initially set in the HTML code. Although they are connected, in some way, with properties, they are not the same thing. In most cases, you should work with properties, and access attributes only when you really need it.

    Attribute values, unlike DOM properties, as noted above, are always strings.

    JavaScript has four methods for performing attribute-related operations:

    • .hasAttribute("attribute_name") – checks if the element has the specified attribute. If the attribute being checked is on the element, then this method returns true , otherwise false .
    • .getAttribute("attribute_name") - Gets the value of the attribute. If the element does not have the specified attribute, then this method returns an empty string ("") or null .
    • .setAttribute("attribute_name", "attribute_value") – sets the specified attribute with the specified value to the element. If the element has the specified attribute, then this method will simply change its value.
    • .removeAttribute("attribute_name") - removes the specified attribute from the element.

    Consider examples.

    Highly interesting example with the value attribute.

    Example with value attribute

    Get the value of the value attribute and the value DOM property:

    // get the value of the value attribute of the element name.getAttribute("value"); // "Bob" // get the value of the DOM property value name.value; // "Bob" // update the value of the value attribute, set it to a new value name.setAttribute("value", "Tom"); // "Tom" // get the DOM value of the property value name.value; // "Tom"

    This example shows that when the value attribute changes, the browser automatically changes the value DOM property accordingly.

    Now let's do the opposite, namely change the value of the DOM property and check if the value of the attribute changes:

    // set a new value to the DOM property value name.value = "(!LANG:John"; // получим значение атрибута value у элемента name.getAttribute("value"); // "Tom" !}

    This example shows that changing a DOM property does not always result in a corresponding change in the attribute. Those. in this case, changing the value DOM property does not change its corresponding attribute.

    The same will happen when the user enters text into this field. The value DOM property will contain the actual value, and the corresponding attribute will contain the original value or the one we set, for example, using the setAttribute method.

    This example shows that it is more correct to always work with DOM properties, and you need to access the attribute only when it is really necessary.

    Even if you need to get the initial value we set in the HTML, you can still use the property. The property that contains the initial value of the value attribute is called defaultValue .

    Name.defaultValue; // Tom

    Another very interesting example, but now with the href attribute.

    href example

    An example where we need to get the value of the link as it was set in the HTML.

    In this example, the href attribute and the href DOM property contain different meanings. The href attribute is what we set in the code, and the DOM property is the full URL. This distinction is dictated by the standard that the browser must cast the href value to the full URL.

    Therefore, if we need to get what is in the attribute, then in this case we cannot do without the getAttribute method.

    Finally, let's take a look at the selected attribute.

    Selected example

    An example that shows how you can get the value of the selected select option:

    An example that shows how to get the selected option values ​​in a select element:

    Another way to work with attributes (attributes property)

    In JavaScript, each element has an attributes property that can be used to retrieve all of its attributes as a NamedNodeMap object.

    This method can be used when you need to, for example iterate over all the attributes of an element.

    An attribute in this collection is accessed by its index or by using the item method. The attributes in this collection are counted from 0.

    For example, let's display all the attributes of some element in the console:

    I LOVE JAVASCRIPT

    Besides, You can also work with this collection using the following methods:

    • .getNamedItem("attribute_name") – gets the value of the specified attribute (if the specified attribute does not exist on the element, then the result will be null).
    • .setNamedItem("item attribute") – adds a new attribute to an element or updates the value of an existing one. To create an attribute, you must use the document.createAttribute() method, which must be passed the name of the attribute as a parameter. After that, the created attribute must be assigned a value using the value property.
    • .removeNamedItem("attribute_name") – removes the specified attribute from the element (returns the removed attribute as a result).

    An example of working with attributes through the getNamedItem, setNamedItem and removeNamedItem methods:

    I LOVE JAVASCRIPT

    Tasks

    • Print to the console all document elements that have an id attribute.
    • Add a title attribute to all images on the page if they don't have this attribute. Attribute value set equal to the value alt attribute.

    You can create a custom binding bindings, which will check the value of a specific observable boolean value before adding or not attributes. See this example:

    Ko.bindingHandlers.attrIf = ( update: function (element, valueAccessor, allBindingsAccessor) ( var h = ko.utils.unwrapObservable(valueAccessor()); var show = ko.utils.unwrapObservable(h._if); if (show) ( ko.bindingHandlers.attr.update(element, valueAccessor, allBindingsAccessor); ) else ( for (var k in h) ( if (h.hasOwnProperty(k) && k.indexOf("_") !== 0) ( $(element).removeAttr(k); ) ) ) ) ); link

    I wish I could just answer @gbs but I can't. My solution would be to have two identical HTML element: one with attribute, without it and a knockout condition to add one of them according to the element. I am also aware of this usual wait, but which solution is more efficient?

    Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

    Syntax

    element.setAttribute( name, value);

    Parameters

    name A DOMString specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute() is called on an HTML element in an HTML document. value A DOMString containing the value to assign to the attribute. Any non-string value specified is automatically converted into a string.

    Boolean attributes are considered to be true if they"re present on the element at all, regardless of their actual value ; as a rule, you should specify the empty string ("") in value (some people use the attribute"s name; this works but is non-standard). See the below for a practical demonstration.

    Since the specified value gets converted into a string, specifying null doesn't necessarily do what you expect. Instead of removing the attribute or setting its value to be null , it instead sets the attribute"s value to the string "null" . If you wish to remove an attribute, call removeAttribute() .

    return value

    Exceptions

    InvalidCharacterError The specified attribute name contains one or more characters which are not valid in attribute names.

    example

    In the following example, setAttribute() is used to set attributes on a .

    HTML

    JavaScript

    var b = document.querySelector("button"); b.setAttribute("name", "helloButton"); b.setAttribute("disabled", "");

    This demonstrates two things:

    • The first call to setAttribute() above shows changing the name attribute"s value to "helloButton". You can see this using your browser"s page inspector (Chrome , Edge , Firefox , Safari).
    • To set the value of a Boolean attribute, such as disabled , you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true . The absence of the attribute means its value is false . By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true , which results in the button being disabled.

    DOM methods dealing with element's attributes:

    Not namespace-aware, most commonly used methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for dealing with Attr nodes directly (seldom used) DOM Level 2 namespace-aware methods for dealing with Attr nodes directly (seldom used)
    setAttribute(DOM 1) setAttributeNS setAttributeNode setAttributeNodeNS
    getAttribute(DOM 1) getAttributeNS getAttributeNode getAttributeNodeNS
    hasAttribute(DOM2) hasAttributeNS - -
    removeAttribute(DOM 1) removeAttributeNS removeAttributeNode -

    Specification

    • DOM Level 2 Core: setAttribute (introduced in DOM Level 1 Core)

    Browser compatibility

    The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

    Update compatibility data on GitHub

    DesktopMobile
    ChromeedgeFirefoxInternet Explorer Operasafariandroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
    setAttributeChrome Full supportYesEdge Full support 12Firefox Full supportYesIE Full support 5

    notes

    Full support 5

    notes

    notes In Internet Explorer 7 and earlier, setAttribute doesn't set styles and removes events when you try to set them.
    Opera Full support YesSafari Full support 6WebView Android Full support YesChrome Android Full support YesFirefox Android Full supportYesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes

    Legend

    Full support Full support See implementation notes. See implementation notes.

    Gecko notes

    Using setAttribute() to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use Element.value instead of Element.setAttribute() .