JS Change Attribute Dom

Attributes in HTML elements can be added, updated, or removed dynamically using JavaScript. The setAttribute, getAttribute, hasAttribute, and removeAttribute methods, as well as property access, are commonly used to manipulate attributes.


setAttribute:

Adds or updates an attribute on an element.

Example
<div id="example">Existing text</div>
<script>
const element = document.getElementById('example');
element.setAttribute('class', 'new-class'); // Sets or updates the 'class' attribute.
element.setAttribute('data-id', '123'); // Adds a custom data attribute.
console.log(element);
</script>

Try it yourself


getAttribute:

Retrieves the value of an attribute.

Example
<div id="example" class="new-class">Existing text</div>
<script>
const element = document.getElementById('example');
const classValue = element.getAttribute('class'); // Retrieves the 'class' attribute value.
console.log(classValue); // Output: new-class
</script>

Try it yourself


removeAttribute:

Removes an attribute from an element.

Example
<div id="example" class="new-class">Existing text</div>
<script>
const element = document.getElementById('example');
element.removeAttribute('class'); // Removes the 'class' attribute.
console.log(element.getAttribute('class')); // Output: null
</script>

Try it yourself


hasAttribute:

Checks if an element has a specific attribute.

Example
<div id="example" class="new-class">Existing text</div>
<script>
const element = document.getElementById('example');
if (element.hasAttribute('class')) {
console.log('The element has a class attribute.');
} else {
console.log('No class attribute found.');
}
</script>

Try it yourself


style:

Add styles in js

Example
<h1>style in js</h1>
<div id="example">Existing text</div>
<script>
const element = document.getElementById('example');
element.style.color = 'white';
element.style.backgroundColor = 'green';
</script>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.