Adding a javascript attribute. Manipulating element attributes in jQuery

The lesson will cover the beginning of the topic: the document object model (javaScript DOM) is the basis of dynamic HTML, methods of accessing objects will be studied and how to handle javascript events

  • Generally an object Is a composite data type that combines many values ​​into a common module and allows you to store and retrieve values ​​on demand by their names.
  • Earlier we have already started acquaintance with the concept in javascript.

  • In javascript there is such a thing as DOM - Document Object Model- the object model of the web page (html pages).
  • 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 is the document object discussed in this topic.

The script element has attributes:

  • defer (waiting for the page to load completely).
  • Example:

    Properties and attributes of the document object in javaScript

    The document object represents a web page.

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

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

    object.property object.attribute object.method ()

    Let's consider an example:

    Example: let the html document have a tag

    My element

    and the css style defined for it (even two styles, the second is useful for the task):

    Necessary:

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

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

      Since this is a javascript language, an 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 an attribute of an object. Object Attribute Are the attributes of the tag. Those. in our case there are two: the class attribute with a value of small and the id attribute. We will work with the class attribute.

      Now let's add javascript code to display the value of the attribute of our object. The code should be located 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"... Let's replace the value of the class attribute with 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 colored blue (class big).

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

    Methods for working with 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 a given attribute:
    • removeAttribute (attr)

    Different ways of working with attributes

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


    ✍ Solution:
    • Let's have a text block:
    • var elem = document.getElementById ("MyElem"); var x = "value";

    • Let's look at several ways to get the value of an attribute (use the alert () method for output):
    • elem.getAttribute ("value")

      elem.getAttribute ("value")

      2.dot notation:

      elem.attributes .value

      elem.attributes.value

      3.bracket notation:


      Set attribute values also in several ways:

      var x = "key"; // key is the name of the attribute, val is the value for the attribute // 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 refer to 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 - the height of the client window
      document.body.clientWidth - client window width


      But the most important thing, as we have already learned, is that through the document object, through special methods, access to all page elements, that is, tags, is carried out.

      Important: With this kind of reference to page tags, the script must be at the end of the element tree, before closing the body! Since by the time the script is executed, all elements must already be "drawn" by the browser on the screen

      Job js8_1... Display 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 the 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(get 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 the data

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

      ...

      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); // print 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 of the 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 through a variable organizes access to all input elements (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, then we indicate its index (the array starts from the zero index).

    ✍ Solution:

      We refer 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, in which the 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);

    In this example, there is only one element, but the reference is made 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 tags form, input, a, select, textarea and a number of others, more rare.

    The document.getElementsByName method will not work with other elements like divs, p, etc.

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

    document.getElementById (roditel) .childNodes;

    document.getElementById (roditel) .childNodes;

    Consider an example in which image tags are placed in a container - a div tag. Thus, the div tag is the parent of the image data, 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 display the values ​​of the array elements with descendants in the modal window, i.e. img tags:

    var myDiv = document.getElementById ("div_for_img"); // refer to the parent container var childMas = myDiv.childNodes; // array of descendants 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 the descendant array. Those. in our example we get a loop:

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

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

  • Other ways to refer to elements
  • Other ways we will consider For example:

    <body> <form name = "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 accessor methods for elements 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); // 4 ...

    ... // 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 accessor methods for elements alert (document.getElementById ("t"). type); // text alert (document.getElementById ("s"). name); // ss alert (document.getElementById ("s"). options.id); // 02 alert (document.getElementById ("o3"). Text); // 4 ...

    Example: In html document create button and text box. Using a script to color the background of the button (the style.backgroundColor property of the button) and display the caption "Hey!" in the textbox (value tribute).

    Html code:

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

    Option 2:

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

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

    Js8_2. Create text box tags according to the image in the picture. Set them to the corresponding (shown in the figure) id attribute values. Add the value "0" to all numeric fields (assuming numeric values) using the script

    Verifying that the form data is entered correctly

    Is the field empty?

    Data entered by users cannot be trusted. It is unreasonable to assume that users will check the data as they enter it. This means you need to use javascript for this.

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


    if (document.getElementById ("name"). value == "") (some actions, for example, displaying a message asking you to fill in the field);

    In addition, you can do without a script. The input tag of the text box has a pattern attribute. its value is a regular expression for validating data in this text field of the form. If attribute is present pattern then the form will not submit until this text box is filled in correctly.
    For example, to check if a field is left empty:

    Text instead of numeric value: isNaN function

    If the field suggests numeric input, and instead the user enters text, then you must use the isNaN function (from the English. "Is not it a number?"), which checks the input data type and returns true if text data is entered instead of numeric data.

    That. if true is returned, then it is necessary to notify the user to enter the correct format, i.e. number.

    if (isNaN (document.getElementById ("minutes"). value)) (alert asking for numeric data);

    Given a page with elements to fill:


    Snippet of 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 = "poditog">
    Tax:<input type = "text" id = "tax">
    Outcome:<input type = "text" id = "itog">
    <input type = "submit" value = "(! LANG: order" onclick = "placeOrder();" > !} </ form> <script type = "text / javascript"> ... </ script>

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

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

    * Perform the assignment also using the pattern attribute of the text fields using.

    Fragment of the script:

    The code is used to build complex conditions passed earlier.

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

    You can create a custom binding bindings, which will check the value of a specific observable boolean 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 elements, one with an attribute, one without, and a knockout condition to add one of them to match the element. I am also aware of this usual expectation, but which solution is more efficient?

    This tutorial is about reading and modifying 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 () to read, add and change attributes
    • removeAttr () to remove attributes

    This lesson explains how to work with the attr () and removeAttr () methods.

    There are special jQuery methods for working with CSS classes, which are described in another tutorial. When working on a project in jQuery, you have to manipulate CSS classes very often, and the class attribute can contain several class names, which makes it much more difficult to work with than other attributes.

    If you are going to work with the values ​​of input fields, then it is better to use the val () method, which not only provides a simplified way of working with the value attribute, but can also read and set values ​​in the selected elements of the select list.

    Reading the value of the attribute

    Reading the value of an attribute of an element is straightforward. You only need to call the attr () method on the jQuery object that contains the element, passing it the name of the attribute 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 the attribute does not exist in the element, it will be added and it will be assigned the given value.
    • If the attribute already exists, its value will be updated specified 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 several attributes at once for an element (or elements) by specifying a map of attribute names and values.
    3. you can dynamically add / change a single attribute for multiple elements using a callback function.

    Setting 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 for multiple elements:

    Setting a few attributes using a map

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

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

    The following example sets two attributes for 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 for multiple elements:

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

    Setting attributes using a callback function

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

    The return function must take two arguments:

    • The index of the position of the currently selected item in the set (starting at zero)
    • the old attribute value for the currently selected element

    The return value of the function is used to override 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. In this way, you can access any property or method of an element from a callback function.

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



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

    Removing 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

    This lesson covered the issues of working with element attributes in jQuery:

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

    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 take a look at what JavaScript methods are for performing operations on attributes.

    How does an attribute differ from a DOM property?

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

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

    For example, a 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 an object. The object here is the DOM node (element).

    An example in which 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"); // print to the console the values ​​of the DOM-properties of the element console.log (brandImg.id); // "brand" console.log (brandImg.className); // "brand" console.log (brandImg.src); // "/logo.png" 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 class is a keyword in JavaScript, it is reserved and cannot be used. Because of this, the developers of the standard decided to use some other name for the match, which was chosen as className.

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

    If an element has a non-standard HTML attribute, then the property corresponding to it in the DOM is not 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, but a DOM property created from it can have another.

    One of these attributes is checked.

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

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

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

    At the same time, you need to know that when we change the DOM property of an element, the corresponding attribute also changes, and vice versa. But this process in browsers is not always done 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 specific 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 id attribute as Id, ID, etc. The same applies to the name of the attribute, which we specify in special JavaScript methods to work with it. But we can refer to the corresponding DOM property only by id and in no other way.

    Working with DOM properties of an element

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

    But in order to access a property of some element, you must first get it. 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:

    Info message text ...

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

    Reading DOM property values:

    // get the value of the DOM property id 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; // "Tooltip text ..."

    Changing DOM property values:

    // to change the value of the DOM property, it just needs to assign a new value alert.title = "(! LANG: New text for the prompt"; // присвоим 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 will print to the console all the values ​​of the classes that the p elements on the page have:

    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 will set all elements with the content class the lang property with the value "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 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 to.

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

    JavaScript has four methods for performing attribute operations:

    • .hasAttribute ("attribute_name") - checks for the presence of the specified attribute on the element. If the element has a checked attribute, 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.

    Let's look at some examples.

    A very interesting example with the value attribute.

    Example with value attribute

    Let's 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 a new value to it name.setAttribute ("value", "Tom"); // "Tom" // get the value of the DOM property value name.value; // "Tom"

    From this example, you can see that when the value attribute changes, the browser automatically changes the DOM value 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" !}

    From this example, you can see that changing a DOM property does not always lead to a corresponding change in the attribute. Those. in this case, changing the value DOM property does not change the corresponding attribute.

    The same will happen when the user enters text in this field. The DOM property value will contain the actual value, and the corresponding attribute will contain the original value or the one that 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 HTML, you can use the property. The property containing the initial value of the value attribute is called defaultValue.

    Name.defaultValue; // Tom

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

    Example with href attribute

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

    In this example, the href attribute and the DOM href property contain different values. 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 match the href value to the full URL.

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

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

    Example with the selected attribute

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

    An example showing how you can 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, for example, to iterate over all the attributes of an element.

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

    For example, let's display all the attributes of a certain element to 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 is absent from the element, then the result will be null).
    • .setNamedItem ("attribute_yzel") - adds a new attribute to an item 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 item (returns the removed attribute as a result).

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

    I LOVE JAVASCRIPT

    Tasks

    • Print to the console all elements of the document that have the id attribute.
    • Add the title attribute to all images on the page if they do not have this attribute. Set the attribute value to the value of the alt attribute.

    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 converted automatically 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 (DOM 2) 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 ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
    setAttributeChrome Full support YesEdge Full support 12Firefox Full support YesIE 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 support YesOpera 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 ().