Javascript element attribute values. Manipulating element attributes with jQuery. Verification of the correctness of the entered data forms

Golovna / Corisna information

At the lesson, the cob will be looked at: the Document Object Model (javaScript DOM) - the basis of dynamic HTML, methods for accessing objects will be looked at and methods for processing javascript

  • In general object- this is a storage type of data, which will change the meaningless value of the main module and allow you to save and win over the value behind their names.
  • Previously, we already learned about the understanding of javascript.

  • Javascript has the same understanding as DOM Document Object Model- Object model of the web-side (html-side).
  • Document tags or, as it seems, document nodes are the whole object.

Let's take a look at the diagrams object hierarchy in JavaScript, and those, de ієrarchії are found in the analysis of this topic document object.

The script element has the following attributes:

  • defer (clearance of the total engagement of the side).
  • Butt:

    Authority and attributes of the document object in javaScript

    The document object is the web page.

    Important: To bring to power those object methods in JavaScript, like when working with other objects, dot notation:

    tobto. the object itself is written with a start, then through a dot i without spaces it is indicated its power, attribute chi method

    object.authority object.attribute object.method()

    Let's look at the example:

    Butt: let html-document є tag

    My element

    ta appointments for new css style(navit two styles, the other is needed for setting):

    Required:

    1. set a new power of the object, give value to it and bring value to it;
    2. enter the value of the object's attribute;
    3. change the value of an object attribute.

    Let's take the task in order:
    ✍ Solutions:

      So how mov javascript, then the object can be guessed and set whether it is power or whether it has any meaning. Ale for the cob we take access to the object (about access to the object will be reported below in this lesson):

      // Required access to object id var element = document.getElementById("MyElem"); element.myProperty = 5; // Assign power alert(element.myProperty); // Displayed in dialog box

      The next task is connected with the attribute of the object. Object attribute- Tse tag attributes. Tobto. our view has two: the class attribute with the values ​​small and the id attribute. Right behind the class attribute.

      Now dodamo the JavaScript to see the value of our object's attribute. The code is guilty buti after main tags:

      // Required access to object id var element = document.getElementById("MyElem"); alert(element.getAttribute("class")); // Displayed in dialog box

      І remaining task: change the value of the attribute. For whom we have style preparations big. Change the value of the class attribute to the style:

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

      As a result, our element will become bigger and more popular with the blue color (class big).

    Now, let's take a look at the presentation of applied methods of work with attributes.

    Attribute Methods in JavaScript

    Attributes can be added, seen and changed. For which special method:

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

    • Rechecking the presence of this attribute:
    • removeAttribute(attr)

    Different ways to work with attributes

    Butt: Enter a value for the value attribute text block.


    ✍ Solutions:
    • Come on є text block:
    • varelem = document.getElementById("MyElem"); var x = "value";

    • Let's take a look at a few ways to retrieve the value of an attribute (to display it, use the 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 dekilcoma in the following 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")

      Authority of the body element

      Through the document object, you can navigate to the body of the document - the body tag - with a lot of power.

      For example, the body tag has two powers: width and height of the customer's window:

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


      And more importantly, as we have already recognized, tse those, that through the document object for the help of special methods, access to all elements of the page, such as tags, is provided.

      Important: With such a transition to the side tags, the script is guilty of being in the element tree before closing the body ! Until the moment the script is finished, all the elements can still be marked by the browser on the screen

      js8_1 manager. Look at the information about the expansion of the window of the browser: for example, "resize browser window 600 x 400"

      Accessing Document Elements in JavaScript

      For access to objects or search for objects, a few options were transferred:

    1. Search by id(or the getElementById method), rotate a specific element
    2. Search for a tag name(or the getElementsByTagName method), rotate the array of elements
    3. Query for the name attribute(or the getElementsByName method), rotate the array of elements
    4. Through batkivsky elements(Removing all the goodies)

    Let's take a look at the skin from the options of the report.

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

      The getElementById() method rotates the element itself, which can be retrieved for data access

      Butt: On the side there is a text field with the attribute id="cake":

      ...

      Necessary


      ✍ Solutions:

      alert(document.getElementById("cake").value); // turn "near the cakes"

      You can vikonate those yourself, realizing the beast to the object through change:

      var a=document.getElementById("cake"); alert(a.value); // view the value of the value attribute, so. text "at the cakes"

    Important: The script is guilty buti obov'yazkovo after the tag!

  • Access to an array of elements through the name of the tag name and after an additional array index
  • Syntax:
    document.getElementsByTagName(name);

    Butt: On the side, there is a text field (input tag) with the value attribute:

    ...

    Necessary: enter the value of the value attribute


    The getElementsByTagName method organizes access to all input elements (that is. to an array of elements input), navigate so that this element is single on the side. To go back to a specific element, for example the first one, then you need to specify the index (the array starts from the zero index).

    ✍ Solutions:

      Reverse to a specific element after the index:

      var a =document.getElementsByTagName("input"); alert(a.value); // turn "near the cakes"

  • Access to an array of elements behind the value of the name attribute
  • Syntax:
    document.getElementsByName(name);

    The getElementsByName("...") method turns array of objects, for which the name attribute is older than the value specified as a parameter to the method. Since there is only one such element on the side, the method rotates the array all the same (only with one single element).


    Butt: admissible in document є element:

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

    AT this butt element one, but zdіysnyuєtsya to the zero element of the array.

    Important: The method works only with these elements, for which the name attribute is passed to the specification: all tags form , input , a , select , textarea and other, more common ones.

    The document.getElementsByName method is not applicable to other elements of type div, p and the like.

  • Access to the home of the Batkiv element
  • Access to javascript buttons vydbuvaєtsya for additional power childNodes. Power to lay the object-batkovі.

    document.getElementById (parent) .childNodes ;

    document.getElementById(parent).childNodes;

    Let's look at the butt, de tags of the image placed in the container - div tag. In this way, the div tag is the father of these images, and the img tags themselves are clearly the caps 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 visible in modal vikno the meaning of the elements in the array from the caps, tobto. img tags:

    var myDiv=document.getElementById("div_for_img"); // go to the container dad var childMas=myDiv.childNodes; // array of headers for (var i = 0; i< childMas.length;i++){ alert(childMas[i].src); }

    Please note that in order to iterate over the elements of an array of fields, you need to manually select a loop. Tobto. our application has a cycle:

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

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

  • Other ways to get to the elements
  • Other ways to look at on the example:

    <body > <formname="f"> <input type="text" id="t"> <input type = "button" id = "b" value = "(!LANG:(!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:

    ... // needless and outdated methods for accessing elements: alert(document.forms[0].name); // f alert(document.forms[0].Elements[0].type); // text alert(document.forms [0]. Elements [2]. Options [1]. // o2 alert(document.f.b.type); // button alert(document.f.s.name); // ss alert(document .f.s.options[1].id); // o2 // shorthand 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); // four ...

    ... // needless old methods for accessing elements: 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 // shorthand 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); // four ...

    Butt: For html documents, create a button and a text field. For the help of the script, change the background of the button (the power of style.backgroundColor of the button) and display "Vitayu!" at the text field (attribute value).

    HTML code:

    document.getElementById("t1").value = "(!LANG:(!LANG:Hi!""; 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 appropriately to the thumbnail image. Give it a specific (specified little) id attribute value. For the help of the script, add to all numeric fields (which pass numeric values) the value "0"

    Verification of the correctness of the entered data forms

    Chi did not leave the field empty?

    Danim cannot be trusted. It is unreasonable to admit that the coristuvachi pіd the hour of the introduction of the data їх їх. So, it is necessary for the chogo to win javascript.

    In order to revise the text field is empty(for example, after filling in the data with the correct data, be it a questionnaire), then turn up to the point of value. As for the meaning of power, there is an empty row (""), then it is necessary to say something about this coristuvach.


    if(document.getElementById("name").value=="")

    In addition, you can do without a script. The input tag of a text field can have a pattern attribute. How this value is shown regularly in the course of rechecking data in a given text field form. What is an attribute pattern, then the form is not enforced until the text field is filled in correctly.
    For example, for re-verification, chi did not leave the field empty:

    Text replace numeric value: isNaN function

    What field is transferring entering a numeric value, and to enter the text, it is necessary to select the isNaN function (from English. "Chi is not a number?"), so that you check the type of data to be entered, and turn true when you enter text data instead of numeric data.

    Incl. If it is set to true , it is necessary to tell the speaker that the format is correct, so that. number.

    if(isNaN(document.getElementById("minutes").value))( prompt to enter numeric data);

    Given a page with elements to fill in:


    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" >
    Khvilin:<input type="text" id="minutes">
    Podbag:<input type="text" id="subitog" >
    Gift:<input type="text" id="tax">
    Podbag:<input type="text" id="total">
    <input type = "submit" value = "(!LANG:(!LANG:submit" onclick = "placeOrder();" > !}!} </form> <script type="text/javascript"> ... </script>

    Name:
    Number of donuts:
    Khvilin:
    Podbag:
    Gift:
    Podbag:

    Required:
    Add the empty space of the fragment to the code, expanded below, in order to check the correctness of filling in the two text fields: im'ya(id="name") hvilin(id="minutes"). Vykoristovyte reverification for empty fields empty ("") that the correct format fills the numeric field (isNaN).

    * Vikonati task also for additional help of the pattern attribute of text fields for help.

    Script snippet:

    At the code they win to inspire folding minds, passed earlier.

    New understanding for you is the click of the function as a summary of the button:
    onclick="placeOrder();"
    By clicking on the button, the placeOrder() function will be called

    Sets the value of attribute on the specified element. that atribut already exists, value is updated; wise 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 name attribute is automatically honored for all short hours when setAttribute() is called an HTML element in an HTML document. value A DOMString Any no-string value specified is converted automatically to string.

    Boolean attributes are considered to be true if they"re present on the element at all, regardless of their actual value ; this works but is non-standard).

    No special values ​​cast to string, specifying null doesn't need to be prior to what you expect. So you choose to run attribute, call removeAttribute() .

    return value

    Exceptions

    InvalidCharacterError The value of the name attribute can be set to one or more characters, since it is not valid in the Name attribute.

    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".
    • To set a Boolean attribute value, like disabled , you can specify any value. Empty string has either name of atribut є recommended values. All matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true . The presence of attribute entries of this value is insignificant. By setting the value of 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 as a rule of thumb methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for separating Attr nodes directly (seldom used) DOM Level 2 namespace-aware methods for spreading 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 compactness of tables on this side is generated from structuring data. If you want to know about your data, click on 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 support YesEdge Full support 12Firefox Full support YesIE Full support 5

    notes

    Full support 5

    notes

    notes For 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

    You can use setAttribute() to modify certain attributes, most notably value in XUL, but inconsistently, as the atribute specifies the default value. In order to win or change the current values, it is your fault to win the power. For example, tag Element.value instead of Element.setAttribute() .

    In these articles, we can recognize DOM-authority and attributes, we can see what stinks look like and how to work with them correctly. Let's take a look at how JavaScript has methods for performing operations on attributes.

    What does the attribute look like DOM authority look like?

    Attributes are all HTML entities, with the help of which we can add individual data to HTML code elements.

    If the browser asks for the first line, it will take the outgoing HTML code. After this wine expands this code and will be on the same DOM substituent. Under the hour of the process HTML-attributes of elements are converted to DOM-authority.

    For example, the browser, when reading an attacking HTML string of code, creates an offensive DOM authority for this element: id, className, src and alt.

    Zvernennya to tsikh authorities JavaScript codes vykonuєtsya as to the authority of the object. The object here is a node (element) DOM.

    For example, taking the value of the DOM authority for the hovered element, and displaying its value in the console:

    // Removing the element var brandImg = document.querySelector("#brand"); // log the value of the DOM authority of the element 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"

    In fact, DOM authority names do not match attribute names. One of these is the class attribute. This attribute sets the DOM power of className . This distinction is due to the fact that class is a JavaScript keyword, it is reserved and cannot be overridden. Through the rozrobniks, the standard was changed to vikoristovuvaty for consistency as a different name, which className was chosen.

    Another aspect of the reasons for this is that the translation of HTML attributes, given to the output code of the document, in the DOM authority does not have to be done one to one.

    If an element has a non-standard HTML attribute, then the authority that validates the DOM is not created.

    Another reason is that the meanings of certain HTML attributes and similar DOM powers can be different. Tobto. an attribute can have one meaning, and DOM-authority, created on the same basis, has another.

    One of these attributes is checked.

    The value of the checked HTML attribute in to this particular type- Tse empty row. Ale, the power to set this DOM attribute to true . Because according to the rules of the standard for setting true, the riddle of which attribute in the HTML code is enough, and if so, it doesn’t matter, as long as the value is there.

    If you do not specify the checked attribute in the HTML code for the input element with the checkbox type, then for the new one in the DOM everything will be set to the checked power, otherwise it will be false.

    Damn it, JavaScript allows you to work with attributes. For which DOM API there are special methods. Ale їх it’s better to beat them only if you really need to practice with them yourself.

    Whenever you need to know that if we change the DOM power of an element, the default attribute will change as well. The whole process in browsers is not fixed one by one.

    Main powers between DOM power and attributes:

    • the value of the attribute is a row, and the value of the DOM-authority is a sing type of data (not a binding row);
    • attribute name is registry-independent, and DOM-authority is registry-independent. Tobto. We can write the HTML code, for example, the HTML id attribute, like Id , ID і etc. The same should be the same and the name of the attribute, as it is indicated to us by special JavaScript methods to work with him. Ale to DOM-authority, we can turn only for ID and not in a different way.

    Working with the DOM power of an element

    The work with the power of the elements of JavaScript, as it was previously assigned, is more important, as with the power of the objects.

    But in order to turn up to the quality of the singing element, you need to take it off the cob. You can extract a DOM element from JavaScript, for example, using the querySelector helper, and a collection of DOM elements, for example, using the querySelectorAll helper.

    As the first butt, let's look at the next HTML element:

    The text of the informational announcement...

    On the basis of the new analysis, it is possible to create a new DOM-authority, their change and addition of new ones.

    Reading the meaning of DOM authorities:

    // Retrieve DOM power value id var alertId = alert.id; // "alert" // take the DOM authority value className var alertClass = alert. className; // "alert alert-info" // takes the DOM authority value title var alertId = alert. title; // "Tip text..."

    Change the value of DOM authorities:

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

    Adding DOM Authorities:

    Alert.lang="en"; // set the authority of the lang value, which is "ru" alert.dir = "ltr"; // set the power of dir equal to "ltr"

    Butt, for example, in the console, all the values ​​of the classes are displayed, for example, in the p elements on the side:

    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 can insert all the elements with the content class, the authority of the lang with the values ​​"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 first set in the HTML code. The stench is hot and pov'yazan with a singing rank with authority, but not the same. Most often, it is necessary to practice with authority, and only once, if necessary, before the attributes.

    Values ​​of attributes, on the basis of DOM-authorities, as it was already assigned more, always in a row.

    JavaScript for specific operations associated with attributes, here are some methods:

    • .hasAttribute("im'ya_attribute") – checks the presence of the specified attribute in the element. If the attribute that is being changed is on the element, then this method turns true , otherwise it turns false .
    • .getAttribute("attribute name") – get attribute value. If there is no element specified, then this method returns an empty row ("") or null .
    • .setAttribute("attribute_name", "attribute_value") – sets the specified attribute from the element's assigned value. If you assign an attribute to an element, then this method simply changes its value.
    • .removeAttribute("im'ya_attribute") - removes attribute values ​​from the element.

    Let's take a look at it.

    duje buttstock with the value attribute.

    Example with attribute

    We take the value of the value attribute and the DOM power of value:

    // Retrieve the value of the value attribute of the element name.getAttribute("value"); // "Bob" // DOM power value taken value name.value; // "Bob" // Change the value of the value attribute, set a new value name.setAttribute("value", "Tom"); // "Tom" // take the DOM power value value name.value; // "Tom"

    For good reason, when you change the value attribute, the browser automatically changes to the new DOM power of value .

    Now let's work it out, first of all, and change the value of DOM authority and change the value of the attribute:

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

    From this point of view, it is clear that you should not change the DOM-authority before changing the attribute. Tobto. In some way, changing the DOM power of value does not change the default attribute..

    You will see it the same way if you enter the text in this field. The DOM-dominant value will change the default value, and the other way around the attribute will be replaced, for example, after the setAttribute helper method.

    This butt shows that it is more correct to practice with DOM-authorities, and it is only necessary to go to the attribute if it is necessary.

    Navigate to the point, if you need to take the first value of value , as we put it in HTML, you can gain power. The power to override the default value of the value attribute is called defaultValue .

    Name.defaultValue; // Tom

    One more arc buttstock, but now with the href attribute.

    Stock with href attribute

    An example, in which we need to take the meaning of the message, as it was inserted into HTML.

    Whose use is the href attribute and the DOM power of href to have different meanings. In the href attribute - those that we inserted in the code, and the DOM authority - the new URL. This difference is dictated by the standard, depending on how the browser is responsible to cast the href value to the full URL.

    Because we need to take into account those that are in the attributes, then without the getAttribute method, we can’t do without the getAttribute method.

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

    Butt with selected attribute

    An example, in which it is shown how you can take the value of the selected option select:

    Here is an example, which shows how you can choose the value of the options in the select element:

    Another way to work with attributes (power attributes)

    In JavaScript, the skin element has the power of attributes, for the help of which you can take all attributes like a NamedNodeMap object.

    Tsey way You may know zastosuvannya, if you need, for example, go through all the attributes of the element.

    Access to the collection's tsієї attribute is given by its index or by the helper method item . The review of the attributes of the collection is conducted from 0.

    For example, we display in the console all the attributes of the current element:

    I LOVE JAVASCRIPT

    Crimea, pratsyuvati s tsієyu collection is also possible for the help of such methods:

    • .getNamedItem("named_attribute") – retrieves the value of the assigned attribute (since the attribute is not assigned to the element, then the result is null).
    • .setNamedItem("attribute_item") – add a new attribute to the element or update the value of the new one. To create an attribute, you must use the document.createAttribute() method, which must be passed the attribute name as a parameter. After which created attribute, it is necessary to give a value for the additional power of value.
    • .removeNamedItem("attribute_name") – removes attribute values ​​from the element (as a result of attribute removal rotation).

    Buttwork with attributes through the getNamedItem, setNamedItem and removeNamedItem methods:

    I LOVE JAVASCRIPT

    manager

    • Type in the console the elements of the document so that the id attribute can be set.
    • Add the title attribute to all images on the side, as they don't have an attribute. Set the value of the attribute equal to the value of the alt attribute.

    You can create a binding that tunes in bindings, as a reverberation of the meaning of the singing watchful logical meaning before adding chi not attributes. tsey butt:

    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 want to just reply to @gbs, but I can't. My decision would have been that the mothers are two the same HTML element: one with an attribute, without another knockout, to add one of them to the element. I also know about tse zvichayne ochіkuvannya, but how about a solution more effective?

    This lesson on assignments reads and changes the attributes of elements in jQuery.

    Attributes are a pair of name / value, as assigned to the elements of the thesis. Apply attributes ( href, title, src, class):

    Here is the summary text

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

    At this lesson, a robot is chosen with the attr() and removeAttr() methods.

    For working with CSS classes, there are special jQuery methods, as described in another lesson. While working on a project in jQuery, you often have to manipulate CSS classes, and the class attribute can replace a few class names, which significantly makes it easier to work with it, compared with other attributes.

    If you choose to work with the values ​​of the input fields, then it's better to use the val() method, which does not only work with the value attribute, but you can also read and set the values ​​for the selected elements in the select list.

    Reading the value of an attribute

    Reading the element attribute value is simple. It is necessary to call the attr() method of the jQuery object to retrieve the element, passing it the name of the attribute to read. Method to turn the value of an attribute:

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

    If your jQuery object is to retrieve a few elements, the attr() method reads the attribute value of only the first element in the set.

    We set the value of attributes

    The attr() method can also be tweaked to add or change the attribute value:

    • Like an attribute don't know in the element, in the future donations And you will be given a given value.
    • Like an attribute already know, yoga meaning will be updated set values.

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

    1. You can add/change the attributes of any element (or a set of elements).
    2. You can add/change the number of attributes at once for the element (or elements) for the additional setting of the map of attribute names and values.
    3. you can dynamically add/change a single attribute for decal elements for the additional rotation function.

    Set one attribute

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

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

    You can also set the same attribute for decal elements:

    We install a sprat of attributes from the selected card

    You can set a number of attributes at once for one or a number of elements for an additional card. The list of name/value pairs looks like this:

    (im'ya1: value1, im'ya2: value2, ...)

    The stepping butt has two attributes set for the img element at once:

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

    You can also set attributes for decal elements:

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

    We set the attributes of the selection of the turning function

    Alternatively, to pass an attribute value to the attr() method, you can pass it to a callback function. This way you can dynamically set the value of an attribute for decal elements depending on the position of the element that has the value of the attribute or other powers.

    The rotary function can take two arguments:

    • Index of position of the flow selected element to the set (starts from zero)
    • old attribute value for flow selected element

    The value that is rotated by the function is overridden to replace the value of the attribute.

    If the current position of the element is that old attribute value, your function can take access to the element itself for help. keyword this. In this way, it is possible to gain access to any kind of power, or to the method of the element with a reversal function.

    The butt has a reverse function to add the alt attribute to the skin image on the side on the image position and the src attribute:

    Following the code of the first image, the mother has the alt attribute with the value "Baby 1: myphoto.jpg" , and the other image has the alt attribute with the value "Baby 2: yourphoto.jpg" .

    Visibility attribute

    To remove an attribute from an element, you need to call the removeAttr() method, passing it the name of the attribute to be removed. 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 to remove a set of elements. The removeAttr() method removes an attribute from the given elements:

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

    Summary

    For this tutorial, we looked at the power of jQuery element attributes:

    • Reading attribute values
    • Setting one attribute
    • Installing a number of different attributes at once
    • Wicked function for dynamic installation value of attributes for a set of elements
    • View attributes from an element

    © 2022 androidas.ru - All about Android