Retrieve all javascript attribute values. Manipulating element attributes in jQuery. The classList property is an object for working with classes

The lesson will cover the beginning of the topic: the document object model (javaScript DOM) is the basis of dynamic HTML, object access methods will be studied and methods of processing javascript events will be considered.

  • In general, an object is a composite data type that combines many values ​​into a common unit and allows values ​​to be stored and retrieved by their names on demand.
  • Earlier we already started getting 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 also say, document nodes are its objects.

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

The script element has the following attributes:

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

    /* Allows js files to be loaded in parallel and executed immediately after loading, without waiting for the rest of the page to be processed */ /* Allows the browser to start loading js files in parallel without stopping further processing of the page. Their execution occurs after complete parsing of the document object model */

    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 when working with other objects, dot notation is used:

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

    object.property object.attribute object.method()

    Let's look at an example:

    Example: let there be a tag in an html document

    My element

    and specific for him css style(even two styles, the second one will be useful for the task):

    .small( color : red ; font-size : small ; ) .big( color : blue ; font-size : big; )

    .small( color:red; font-size:small; ) .big( color:blue; font-size:big; )

    Necessary:

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

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

    Since this javascript language, then the object can be invented and assigned 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):

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

    The next task is related to an object attribute. An object attribute is the tag's 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 javascript code to display the attribute value of our object. The code must be after main tags:

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

    And the last task: changing the attribute value. We have a style for this. "big". Let's replace the value of the class attribute with this style:

    // access 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, deleted, and modified. 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 value attribute of a text block.


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

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

      elem.getAttribute("value")

      2. dot notation:

      elem.attributes.value

      elem.attributes.value

      3. bracket notation:

      var element = document.getElementById("t1"); alert(...) element.setAttribute(...);


      You can also set attribute values ​​in several ways:

      var x = "key"; // key - attribute name, val - 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 access the body of the document - the body tag - with some useful properties.

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

      document.body.clientHeight — height of the client window
      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, access is provided to all page elements, that is, tags.

      Important: When accessing page tags in this way, the script must be at the end of the element tree, before 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 . Show 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 to access or search for objects:

  • Search by id (or getElementById method), returns a specific element
  • Search by tag name (or getElementsByTagName method), returns an array of elements
  • Search by name attribute (or getElementsByName method), returns an array of elements
  • Via parent elements (getting all children)
  • Let's consider each of the options in more detail.

  • Accessing an element via its id attribute
  • 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 id="cake" attribute:

    ...

    Necessary


    ✍ Solution:

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

      You can do the same thing by accessing the object through a variable:

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

    Important: The script must be located after the tag!

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

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

    ...

    Required: display the value of its value attribute


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

    ✍ Solution:

      We access 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 an 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);

    IN in this example there is only one element, but access 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 form , input , a , select , textarea and a number of other, more rare, tags.

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

  • Accessing descendants of a parent element
  • Children are accessed in javascript through the childNodes property. The property belongs to the parent object.

    document.getElementById(roditel).childNodes;

    document.getElementById(roditel).childNodes;

    Let's look at an example where image tags are placed in a container called a div tag. Thus, the div tag is the parent of the image data, and the img tags themselves are, accordingly, children of the div tag:

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

    var myDiv=document.getElementById("div_for_img"); // access 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 through the elements of a descendant array. 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
  • Let's look at other methods using an example:

    1 3 4

    1 3 4

    Access:

    ... // unwanted and deprecated 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 methods for accessing 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 deprecated element access methods: 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 methods for accessing 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 an HTML document, create a button and a text field. Using a script, color the button background (style.backgroundColor property of the button) and display the inscription "Hello!" in the text field (value attribute).

    HTML code:

    document.getElementById("t1").value = "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";

    Task Js8_2. Create text field tags as shown in the image. Give them the corresponding (shown in the figure) id attribute values. Using a script, add the value “0” to all numeric fields (assuming numeric values)

    Checking that the form data is entered correctly

    Is the field left empty?

    User input cannot be trusted. It is unreasonable to assume that users will check data when entering data. This means you need to use javascript for this.

    In order to check whether the text field is left 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 empty line(""), which means 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 out a field);

    In addition, you can do without a script. At the input tag text field there is a pattern attribute. its value is indicated regular expression to validate the data in a given form text field. If the attribute is present pattern, then the form will not be submitted until this text field is filled out correctly.
    For example, to check if a field is left empty:

    Text instead numerical value: function isNaN

    If a field requires entering a numeric value, but instead the user enters text, then the isNaN function must be used. "is not a number?"), which checks the type of input data and returns true if text data is entered instead of numeric data.

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

    if(isNaN(document.getElementById("minutes").value))( alert requiring 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 Name:
    Number of donuts:
    Minutes:
    Summary:
    Tax:
    Result:
    ...

    Name:
    Number of donuts:
    Minutes:
    Summary:
    Tax:
    Result:
    ...

    Necessary:
    Complete 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 checks to ensure that the field is left empty ("") and that the numeric field is filled in correctly (isNaN).

    * Perform the task also with the pattern attribute of text fields using .

    Script fragment:

    The code uses previously learned conditions to build complex conditions.

    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

    You can create a custom binding binding, 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 element: one with the attribute, without it and a knockout condition to add one of them according to the element. I'm also aware of this common expectation, but which solution is more efficient?

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

    Attributes are a name/value pair that are assigned to elements in a tag. Examples of attributes ( href, title, src, class):

    Here is the summary text

    • attr() to read, add and change attributes
    • removeAttr() to remove attributes

    This lesson covers working with the attr() and removeAttr() methods.

    There are special jQuery methods for working with CSS classes, which are described in another lesson. When working on a project in jQuery, you have to manipulate CSS classes a lot, and the class attribute can contain multiple class names, which makes working with it much more complex 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 attribute value

    Reading the value of an element's attribute is simple. 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 attribute value:

    // Print 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 reads the attribute values ​​for only 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 be added and it will be assigned the specified value.
    • If attribute already exists, its value will be updated given value.

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

  • You can add/change attributes for any element (or set of elements).
  • You can add/change several attributes at once for an element (or elements) by specifying a map of attribute names and values.
  • you can dynamically add/change a single attribute for multiple elements using a callback function.
  • Set one attribute

    To set or change an element's attribute, you need to call the attr() method specifying the attribute name and value. For example:

    // Change the value of the "href" attribute of the #myLink element to the value "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 several attributes using a map

    You can set multiple attributes at once on 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 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 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 way you can dynamically set attribute values ​​for multiple elements based on 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 (starts at zero)
    • old attribute value for the currently selected element

    The value returned by the function is used to replace the attribute value.

    In addition to the element's current position and the attribute's old value, your function can access the element itself using the key words this. This way, you can access any element property or method from the callback function.

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

    $(init); function init() ( // Set the "alt" attribute for all "img" elements $("img").attr("alt", setAltText); function setAltText(index, attributeValue) ( ​​return ("Figure " + (index +1) + ": " + this.src); ) )

    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, you need to 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 specified attribute from all elements:

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

    Summary

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

    • Reading Attribute Values
    • Setting one attribute
    • Setting several different attributes at once
    • Using a callback function to dynamically set attribute values ​​on a set of elements
    • Removing attributes from an element

    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 Hello World 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

    Desktop Mobile Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung InternetsetAttribute
    Chrome 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() .

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

    What is the difference between an attribute and a DOM property?

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

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

    For example, the browser, when reading the following line of HTML 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 a DOM node (element).

    An example in which we get the values ​​of DOM properties for the element given above and output their values ​​to the console:

    // get the element var brandImg = document.querySelector("#brand"); // display the values ​​of the element's DOM properties to the console 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 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 compliance, 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 a property corresponding to it in the DOM is not created.

    // get the element mydiv = document.querySelector("#mydiv"); // get the value of the element's alt property and output it to the console console.log(mydiv.alt); // undefined // get the value of the element's alt attribute and output it to the console console.log(mydiv.getAttribute("alt")); // "..."

    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 based on it can have another.

    One of these attributes is checked.

    The value of the checked HTML attribute in this case is an empty string. But, the property corresponding to a given attribute in the DOM will have 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.

    Moreover, even if we do not specify the checked attribute in the HTML code for an input element with type checkbox, then a 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 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 performed one to one.

    The main differences between DOM properties and attributes are:

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

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

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

    As a first example, consider the following HTML element:

    Information message text... var alert = document.querySelector("#alert"); // get the element

    Based on it, we will analyze how to obtain DOM properties, change them and add new ones.

    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 value of the DOM property title var alertId = alert.title; // "Help 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 = "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 will output to the console all the class values ​​that the 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 to all elements with the content class 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 it.

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

    JavaScript has four methods for performing attribute-related operations:

    • .hasAttribute("attribute_name") – checks whether the element has the specified attribute. If the element has the attribute being checked, then this method returns true, otherwise false.
    • .getAttribute("attribute_name") – gets the attribute value. 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 then simply change its value.
    • .removeAttribute("attribute_name") - removes the specified attribute from the element.

    Let's look at examples.

    A very interesting example with the value attribute.

    Example with the value attribute var name = document.querySelector("input"); // get the element

    Let's get the value of the value attribute and the DOM property value:

    // 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 value of the DOM 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 whether the attribute value changes:

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

    This example shows 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 its corresponding attribute.

    The same thing will happen when the user enters text into this field. The DOM property value 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 in the case where you need to get the initial value that 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 value of the link as it was set in the HTML.

    var page2 = document.querySelector("#link"); page2.getAttribute("href"); // page2.html page2.href; // full URL, for example: http://localhost/page2.html

    In this example, the href attribute and the href DOM property contain different values. The href attribute is what we set in the code, and the DOM property is the full URL. This difference is dictated by the standard that the browser must resolve 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 look at the selected attribute.

    Example with the selected attribute

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

    no rating 1 2 3 4 5 // get the select element var mark = document.querySelector("#mark"); // 1 way mark.querySelector("option:checked").value; // Method 2 mark.value;

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

    no rating 1 2 3 4 5 // get the select element var mark = document.querySelector("#mark"); // Method 1 (by creating an array and filling it with the values ​​of the selected options) var arr = ; for (var i = 0, length = mark.options.length; i< length; i++) { if (mark.options[i].selected) { arr.push(mark.options[i].value); } } // 2 способ (более современный, с использованием DOM-свойства selectedOptions) var arr = Array.from(mark.selectedOptions, option =>option.value)

    Another way to work with attributes (the attributes property)

    In JavaScript, each element has an attributes property, which 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 through all the attributes of an element.

    An attribute in this collection is accessed by its index or by using the item method. 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

    // get the element by its identifier message var message = document.querySelector("#message"); // get its attributes var attrs = message.attributes; // go through all the attributes using a loop (attrs.length – number of attributes) for (var i = 0, length = attrs.length; i< length; i++) { // attrs[i] или attrs.item(i) – обращение к атрибуту в коллекции по его порядковому номеру // attrs[i].name – имя атрибута // attrs[i].value – значение атрибута (с помощью него можно также изменить значение атрибута) console.log(attrs[i].name + " = " + attrs[i].value); // или с помощью метода item console.log(attrs.item(i).name + " = " + attrs.item(i).value); // пример как можно изменить значение через свойство value // if (attrs[i].name === "class") { // attr[i].value = "info"; // } } // в результате выполнения: // id = message // class = text // style = text-align: center;

    In addition, 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 not present on the element, then the result will be null).
    • .setNamedItem("attribute_node") – 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 attribute name as a parameter. The created attribute must then be assigned a value using the value property.
    • .removeNamedItem("attribute_name") – removes the specified attribute from an element (returns the removed attribute as the result).

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

    I LOVE JAVASCRIPT

    // get the element by its identifier message var message = document.querySelector("#message"); // get its attributes var attrs = message.attributes; // Task No. 1. Get the value of the id attribute console.log(attrs.getNamedItem("id")); // Task No. 2. Set the attribute (if it exists, then change its value, otherwise add a new one) // create the style attribute and save it to the attrStyle variable var attrStyle = document.createAttribute("style"); // assign a value to the attribute using the value property attrStyle.value = "text-align: left;"; // устанавливаем атрибут элементу attrs.setNamedItem(attrStyle); // Задача №3. удалить атрибут class у элемента attrs.removeNamedItem("class"); !}

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