4 of 119 menu

The attr method

The attr method allows you to get and change any attribute of an element.

It is important not to confuse properties and attributes of elements. When creating a DOM tree, attributes are translated into the corresponding DOM properties of elements. Their names do not always match, as do their values. Some properties may also not have corresponding attributes, they can only be obtained and set using the prop method, for example the tagName property.

Syntax

Getting the attribute value:

$(selector).attr(attribute name);

Changing the attribute value:

$(selector).attr(attribute name, new value);

Changing the values ​​of multiple attributes:

$(selector).attr({first first top former maiden opening premier pioneer premiere primus virgin first-ever_attribute: new_meaning, second_attribute: new_meaning, ...});

Applying a function to each element in a set:

$(selector).attr(attribute name, function(number in set, current attribute value));

Example

In the following example, we get the input by its id and print the value of its attribute value:

<input type="text" value="!!!" id="test"> let value = $('#test').attr('value'); console.log(value);

Example

Now let's write the new value 'www' into the same attribute:

<input type="text" value="!!!" id="test"> $('#test').attr('value', 'www');

HTML the code will look like this:

<input type="text" value="www" id="test">

Example

Let's change the type and value attributes at the same time:

<input type="text" value="!!!" id="test"> $('#test').attr({value: 'www', type: 'password'});

HTML the code will look like this:

<input type="password" value="www" id="test">

Example

Let's change the value attribute for each input - add the ordinal number of the element in the set to the current value:

<input type="text" value="aaa"> <input type="text" value="bbb"> <input type="text" value="ccc"> $('input').attr('value', function(index, value) { return value + ' ' + index; });

HTML the code will look like this:

<input type="text" value="aaa 1"> <input type="text" value="bbb 2"> <input type="text" value="ccc 3">

See also

  • method removeAttr,
    which allows you to remove attributes from elements
  • method prop,
    which allows you to work with the properties of elements
  • method val,
    which allows you to get and change the current value of an element
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline