JavaScript DOM Manipulation Method Every Developer Should Know

JavaScript DOM Manipulation Method Every Developer Should Know
September 18, 2023

1. Selecting Elements:

  • document.getElementById('id'): Gets an element by its ID.
  • document.querySelector('selector'): Gets the first element that matches the provided CSS selector.
  • document.querySelectorAll('selector'): Gets all elements that match the provided CSS selector.
let div = document.getElementById('myDiv');
let firstButton = document.querySelector('button');
let allButtons = document.querySelectorAll('button');


2. Changing Text Content:

  • element.textContent: Gets or sets the text content of an element.
div.textContent = 'New text content!';


3. Changing HTML Content:

  • element.innerHTML: Gets or sets the HTML content inside an element.
div.innerHTML = '<strong>This is bold text.</strong>';


4. Manipulating Attributes:

  • element.getAttribute('attribute'): Gets the value of an attribute.
  • element.setAttribute('attribute', 'value'): Sets the value of an attribute.
let link = document.querySelector('a');
let hrefValue = link.getAttribute('href');
link.setAttribute('href', 'https://www.example.com');


5. Adding and Removing Classes:

  • element.classList.add('class'): Adds a class to an element.
  • element.classList.remove('class'): Removes a class from an element.
  • element.classList.toggle('class'): Toggles a class (adds it if it doesnโ€™t exist, removes it if it does).
div.classList.add('highlight');
div.classList.remove('old-highlight');
div.classList.toggle('toggle-class');


6. Creating and Adding New Elements:

  • document.createElement('elementName'): Creates a new DOM element.
let newPara = document.createElement('p');
newPara.textContent = 'This is a new paragraph.';
div.appendChild(newPara); // Adds the new paragraph as a child of the div.


7. Removing Elements:

  • element.removeChild(childElement): Removes a child element from the specified element.
  • element.remove(): Removes the element directly.
div.removeChild(newPara);
// or 
newPara.remove();


Event Listeners:

  • Use element.addEventListener('event', function) to respond to user interactions.
firstButton.addEventListener('click', function() {
    alert('Button was clicked!');
});











Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

โ€Œ

โ€Œ

โ€Œ

โ€Œ

โ€Œ

โ€Œ

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates