DOM - Node attribute

1 - About

attributes representation in the DOM.

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

3 - Management

3.1 - Get

3.1.1 - 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:

3.1.2 - 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:

3.2 - 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:

3.3 - Remove


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap