Manipulation Attributes in JavaScript

Attributes

The attributes property returns a live collection of all attribute nodes registered to the specified node. It is a read-only property.

Syntax:-
Element.attributes[index/key]

Attr Object

Properties

  • name (do not use nodeName)
  • value (do not use nodeValue or textContent or appendChild() or insertBefore( ) or removeChild( ) or replaceChild( ) these all are deprecated for attr object)

Methods

  • setAttribute( )
  • getAttribute( )
  • removeAttribute( )

setAttribute( )

This method is used to set 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. We should not use this method to set inline style as it will overwrite other CSS properties.

Syntax:-
Element.setAttribute(name, value);
Element.setAttribute(“style”, “css properties: value”);

Ex: –
p.setAttribute(“id”, “mydiv”);
p.setAttribute(“style”, “font-size: 80px”);

getAttribute( )

The getAttribute() 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 “ ”.

Syntax: –
var attribute = element.getAttribute(attributeName);

removeAttribute( )

This method is used to remove an attribute from the specified element.

Syntax: –
element.removeAttribute(attrName);

hasAttribute( )

The hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.

Syntax:-
var result = element.hasAttribute(attr_name);

Tagged : / / / /
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x