I am using below HTML for my code.
<body>
<div id="myId" class="oldClass">
This is the original content of the element with ID "myId".
</div>
</body>
I am perform DOM Manipulation
using below JavaScript Code:
const myElement = document.getElementById('myId');
myElement.setAttribute('data-example', 'value');
console.log(myElement);
myElement.removeAttribute('data-example');
console.log(myElement);
However, first console.log() statement
is not displaying the data-example
property.
<div id="myId" class="oldClass">
This is the original content of the element with ID "myId".
</div>
2
Answers
The issue you’re experiencing is related to how the browser processes console.log() and the way it handles DOM elements. When you use console.log(myElement), it logs a reference to the DOM node, not a static snapshot of the node at that moment in time. If you manipulate the DOM after logging, those changes will be reflected in the logged element reference when you expand it in the browser’s developer tools.
To avoid this confusion and capture the element as it exists when you log it, you can log the specific attributes or values directly, rather than the element reference.
The
setAttribute()
method in JavaScript is used to add a new attribute or modify an existing attribute of an element. However, theconsole.log()
statement might not display the updated attribute in all browsers’ console because it might not have been updated in the console’s representation of the element at the time of logging.Use the
getAttribute()
method to retrieve the value of the newly added attribute:The
getAttribute()
method is used to display the value of the data-example attribute, which confirms that it has been added to the element.Keep in mind that the
console.log()
statement might not always display the most up-to-date version of the element, especially when dealing with asynchronous code or when attributes are added or removed quickly. It’s always a good practice to double-check the attributes using the appropriate methods likegetAttribute()
.Hope you got your solution. 🙂