skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. The setAttribute() method in JavaScript is used to add a new attribute or modify an existing attribute of an element. However, the console.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:

    const myElement = document.getElementById('myId');
    
    myElement.setAttribute('data-example', 'value');
    console.log(myElement.getAttribute('data-example')); // Output: value
    
    console.log(myElement); // Output: <div id="myId" class="oldClass">...</div>
    myElement.removeAttribute('data-example');
    
    console.log(myElement); // Output: <div id="myId" class="oldClass">...</div>
    

    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 like getAttribute().

    Hope you got your solution. 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search