Table of Contents

DOM - Attribute

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

<p>My sweat suit is <span style="color: green">green</span> </p>
spanElement = document.querySelector('body>p>span');
style = spanElement.getAttribute ('style');
console.log("The style attribute has the value: ("+style + ")");

Get Jquery

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

Set

<p>My sweat suit is <span style="color: green">green</span> </p>
spanElement = document.querySelector('body>p>span');
spanElement.setAttribute ('style','color:red');

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