Javascript get attribute by name

Get the value of the class attribute of an element:

The getAttribute() method returns the value of the attribute with the specified name, of an element.

Use the getAttributeNode() method if you want to return the attribute as an Attr object.

Browser Compatibility

Syntax

element.getAttribute(attribute_name)

Parameter Values

Return Value

A String, representing the specified attribute’s value.

Note: If the attribute does not exist, the return value is null or an empty string («»).

More Examples

Get the value of the target attribute of an element:

let x = document.getElementById("myAnchor").getAttribute("target");
!DOCTYPE html> html> body> Read about the !-- w ww . d e m o 2 s . c o m --> a id="myAnchor" href="https://demo2s.com" target="_blank">website . p>Click the button to display the value of the target attribute of the link above. button onclick="myFunction()">Test p id="demo">  script> function myFunction() < let x = document.getElementById("myAnchor").getAttribute("target"); document.getElementById("demo").innerHTML = x; >   

Example

Get the value of the onclick event attribute of a element:

let x = document.getElementById("myBtn").getAttribute("onclick");
!DOCTYPE html> html> body> p>Click the button to display the value of the onclick attribute of the button element. button id="myBtn" onclick="myFunction()">Test p id="demo">  script> function myFunction() < let x = document.getElementById("myBtn").getAttribute("onclick"); document.getElementById("demo").innerHTML = x; >   

  • Javascript DOM Element grab focus
  • Javascript DOM Element Get closest element by CSS selector
  • Javascript DOM Element exit Full screen mode
  • Javascript DOM Element get Attribute by name
  • Javascript DOM Element get Attribute Node by name
  • Javascript DOM Element get Bounding Client Rectangle
  • Javascript DOM Element get children Elements By Class Name

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Element: getAttribute() method

The getAttribute() method of the Element interface returns the value of a specified attribute on the element.

If the given attribute does not exist, the value returned will either be null or «» (the empty string); see Non-existing attributes for details.

Syntax

getAttribute(attributeName) 

Parameters

Return value

A string containing the value of attributeName .

Examples

// in a console const div1 = document.getElementById("div1"); //=> 
Hi Champ!
const exampleAttr = div1.getAttribute("id"); //=> "div1" const align = div1.getAttribute("align"); //=> null

Description

Lower casing

When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding.

Non-existing attributes

All modern web browsers return null when the specified attribute does not exist on the specified element.

Retrieving nonce values

For security reasons, CSP nonces from non-script sources, such as CSS selectors, and .getAttribute(«nonce») calls are hidden.

let nonce = script.getAttribute("nonce"); // returns empty string 

Instead of retrieving the nonce from the content attribute, use the nonce property:

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

.get Attribute ( )

Метод get Attribute ( ) позволяет получить значение указанного атрибута у HTML-элемента. Если атрибута нет, то метод вернёт null .

Как пишется

Скопировать ссылку «Как пишется» Скопировано

get Attribute ( ) принимает один аргумент – строку с именем атрибута. В ответ метод возвращает значение атрибута в виде строки или null , если атрибута нет на элементе.

  script type="application/json" id="hydration"> script>      
 const scriptElement = document.querySelector('script') console.log(scriptElement.getAttribute('type'))// 'application/json'console.log(scriptElement.getAttribute('id'))// 'hydration'console.log(scriptElement.getAttribute('class'))// null const scriptElement = document.querySelector('script') console.log(scriptElement.getAttribute('type')) // 'application/json' console.log(scriptElement.getAttribute('id')) // 'hydration' console.log(scriptElement.getAttribute('class')) // null      

Как понять

Скопировать ссылку «Как понять» Скопировано

Существует множество стандартных HTML-атрибутов, и разработчики могут задавать элементу свои собственные атрибуты. Метод get Attribute ( ) является универсальным способом прочитать значение любого атрибута.

Не все атрибуты имеет смысл считывать с помощью get Attribute ( ) . Например, атрибут hidden лучше читать из поля hidden DOM-элемента, а дата-атрибуты — из поля dataset .

Сравним два варианта получения значения атрибута. Возьмём элемент и считаем его атрибуты:

  div data-color="red" hidden>Ошибка!div>      
 const element = document.querySelector('div') console.log(element.hidden)// trueconsole.log(element.getAttribute('hidden'))// "" – пустая строка, т.к строкового значения у атрибута нет console.log(element.dataset.color)// "red"console.log(element.getAttribute('data-color'))// "red" const element = document.querySelector('div') console.log(element.hidden) // true console.log(element.getAttribute('hidden')) // "" – пустая строка, т.к строкового значения у атрибута нет console.log(element.dataset.color) // "red" console.log(element.getAttribute('data-color')) // "red"      

Источник

HTML DOM Element getAttribute()

Get the value of the target attribute of an element:

Description

The getAttribute() method returns the value of an element’s attribute.

See Also:

Tutorial:

Syntax

Parameters

Return Value

More Examples

Get the value of the onclick attribute of a element:

Browser Support

element.getAttribute is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Вывод русских символов php
Оцените статью