Attribute manipulation with DOM

About

attributes representation in the DOM.

Node attributes are not included as children in the DOM hierarchy but are properties of an element.

Management

Get

Get Pure Javascript

  • The HTML with the style attribute that we want to change
<p>My sweat suit is <span style="color: green">green</span> </p>
spanElement = document.querySelector('body>p>span');
  • Get the attribute value
style = spanElement.getAttribute ('style');
console.log("The style attribute has the value: ("+style + ")");
  • Result:

Get Jquery

  • The library
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  • The HTML with the data-attr to get the value from
<span data-attr="You got me"></span>
  • The code that outputs the value of the data-attr
let attrValue = $('span').attr('data-attr');
console.log('The value of the data-attr attribute is : '+attrValue);
  • Result:

Set

  • The HTML with the style attribute that we want to change
<p>My sweat suit is <span style="color: green">green</span> </p>
spanElement = document.querySelector('body>p>span');
  • Set the attribute to the color red
spanElement.setAttribute ('style','color:red');
  • Result:

Dom Attribute Set To Color Red

Remove

element.removeAttribute

With element.removeAttribute(attrName).

Demo:

<button style="color:white;background:steelblue">Delete my style</button>
document.querySelector('button').addEventListener("click", function (event) { 
    event.target.removeAttribute("style"); 
});

Jquery.removeAttr

With JQuery, you would use removeAttr





Discover More
DOM - Element

An element is the most common type of node in the DOM. When you want to do something to an element, first you need to select it. A dom element is generally the memory representation of: an HTML element...
DOM - Entity Node

Entity processing in the DOM. Like Attribute nodes, Entity nodes do not appear as children of DOM nodes.
Domtree
DOM - Node

In DOM, every markup in an (XML|HTML) document is a node represented in a tree view. Every DOM node has at least: a , a name, and a value, which might or might not be empty. Node Type...
HTML - Attribute

HTML An attribute in HTML is an XML attribute of an HTML element Attribute names are TR/html-markup/documents.htmlcase-insensitive. Classes and IDs are attributes used in the selection of element....
HTML - Data attributes

Data (Key value) can be included for processing by a script using the data-=“” attributes. css attribute function Output: With an attribute selector, you can select the nodes with a certain...



Share this page:
Follow us:
Task Runner