JavaScript Interview Questions
JavaScript
Web DevelopmentFrontendBackendQuestion 10
How do you manipulate the DOM in JavaScript?
Answer:
DOM (Document Object Model) manipulation in JavaScript allows you to dynamically change the content, structure, and style of a web page. This can be done using various methods provided by the DOM API, such as getElementById
, getElementsByClassName
, querySelector
, querySelectorAll
, createElement
, appendChild
, and removeChild
. These methods enable you to select, create, and modify HTML elements in real-time, enhancing user interactivity.
Here is an example demonstrating some common DOM manipulation techniques:
// Selecting an element by ID
let element = document.getElementById('myElement');
// Changing the inner HTML content
element.innerHTML = 'Hello, World!';
// Creating a new element
let newElement = document.createElement('div');
newElement.innerHTML = 'New Element';
// Appending the new element to an existing element
document.body.appendChild(newElement);
// Removing an element
let removeElement = document.getElementById('removeMe');
removeElement.parentNode.removeChild(removeElement);
In this example, we select an element by its ID, change its inner HTML, create a new div element, append it to the body, and finally remove an element by its ID.