JavaScript DOM Code examples Questions with Solutions

JavaScript DOM Examples

What is the DOM? Explain the concept of the DOM hierarchy.

Solution:

The Document Object Model (DOM) is a cross-platform and language-independent application programming interface that treats an HTML, XHTML, or XML document as a tree structure where each node represents a part of the document. In simple terms, it is an interface between the HTML content and JavaScript code. The DOM hierarchy refers to the parent-child relationship between the nodes in the tree-like structure of the document. For example, the body element is the parent of all other elements on the page, and its child elements are the other elements contained within it.

Code:

// Accessing the DOM hierarchy

console.log(document.body); // returns the body element

console.log(document.body.childNodes); // returns an array of child nodes

What is the difference between innerHTML and innerText in JavaScript?

Solution:

The innerHTML property is used to get or set the HTML content of an element, whereas innerText is used to get or set the text content of an element. The innerHTML property returns the content of the element, including any HTML tags, while innerText returns only the text content, without any HTML tags.

Code:

// Setting the innerHTML and innerText of an element

document.getElementById(“my-element”).innerHTML = “<p>Hello, world!</p>”; // sets the innerHTML to “<p>Hello, world!</p>”

document.getElementById(“my-element”).innerText = “<p>Hello, world!</p>”; // sets the innerText to “<p>Hello, world!</p>”

What is event bubbling in JavaScript?

Solution:

Event bubbling is a phenomenon in JavaScript where when an event is triggered on an element, it also triggers the same event on all its parent elements in the DOM hierarchy, up to the root element. This means that if you click on a child element, the click event will be triggered on the child, the parent, the grandparent, and so on, until it reaches the root element.

Code:

<!– HTML –>

<div id=”parent”>

  <div id=”child”>

    Click me!

  </div>

</div>

<script>

// JavaScript

document.getElementById(“child”).addEventListener(“click”, function() {

  console.log(“Child clicked”);

});

document.getElementById(“parent”).addEventListener(“click”, function() {

  console.log(“Parent clicked”);

});

</script>

If you click on the child element, the output will be:

Copy code

Child clicked

Parent clicked

What is the difference between document.ready and window.onload in JavaScript?

Solution:

document.ready and window.onload are both events in JavaScript that are triggered when a web page is loaded. The document.ready event is fired as soon as the DOM hierarchy is fully loaded, while the window.onload event is fired when the entire page, including all its resources (images, CSS, JavaScript files, etc.), is fully loaded.

Code:

// Using the document.ready event

$(document).ready(function() {

  // code to execute when the DOM hierarchy is fully loaded

});

// Using the window.onload event

window.onload = function() {

  // code to execute when the entire page is fully loaded

};

What is the difference between querySelector and querySelectorAll in JavaScript?

Solution:

querySelector and querySelectorAll are both methods in JavaScript that are used to select elements from the DOM hierarchy. The main difference between the two is that querySelector returns only the first element that matches the specified selector, while querySelectorAll returns a NodeList containing all the elements that match the selector.

Code:

// Using querySelector to select the first element that matches the selector

document.querySelector(“.my-class”);

// Using querySelectorAll to select all elements that match the selector

document.querySelectorAll(“.my-class”);

What is the difference between appendChild and insertBefore in JavaScript?

Solution:

appendChild and insertBefore are both methods in JavaScript that are used to add elements to the DOM hierarchy. The main difference between the two is that appendChild adds the element to the end of the child node list of the parent element, while insertBefore adds the element before a specified child element.

Code:

// Using appendChild to add an element to the end of the parent’s child node list

var newElement = document.createElement(“div”);

document.getElementById(“parent”).appendChild(newElement);

// Using insertBefore to add an element before a specified child element

var newElement = document.createElement(“div”);

var referenceElement = document.getElementById(“reference”);

document.getElementById(“parent”).insertBefore(newElement, referenceElement);

How do you remove an element from the DOM hierarchy in JavaScript?

Solution:

To remove an element from the DOM hierarchy in JavaScript, you can use the removeChild method of the parent element. This method removes the specified child element from the parent’s child node list.

Code:

// Using removeChild to remove an element from the DOM hierarchy

var elementToRemove = document.getElementById(“element-to-remove”);

elementToRemove.parentNode.removeChild(elementToRemove);

How do you create a new element in JavaScript?

Solution:

To create a new element in JavaScript, you can use the createElement method of the document object. This method creates a new element with the specified tag name.

Code:

// Using createElement to create a new element

var newElement = document.createElement(“div”);

What is the difference between getAttribute and setAttribute in JavaScript?

Solution:

getAttribute and setAttribute are both methods in JavaScript that are used to get and set attributes of an element, respectively. The getAttribute method returns the value of the specified attribute of the element, while the setAttribute method sets the value of the specified attribute.

Code:

// Using getAttribute to get the value of an attribute

var attributeValue = document.getElementById(“my-element”).getAttribute(“data-attribute”);

// Using setAttribute to set the value of an attribute

document.getElementById(“my-element”).setAttribute(“data-attribute”, “new value”);

How do you add a class to an element in JavaScript?

Solution:

To add a class to an element in JavaScript, you can use the classList.add method of the element. This method adds the specified class to the element’s class list.

Code:

// Using classList.add to add a class to an element

document.getElementById(“my-element”).classList.add(“my-class”);

How do you check if an element has a specific class in JavaScript?

Solution:

To check if an element has a specific class in JavaScript, you can use the classList.contains method of the element. This method returns a boolean value indicating whether the specified class is in the element’s class list.

Code:

// Using classList.contains to check if an element has a specific class

var hasClass = document.getElementById(“my-element”).classList.contains(“my-class”);

How do you add an event listener to an element in JavaScript?

Solution:

To add an event listener to an element in JavaScript, you can use the addEventListener method of the element. This method takes two arguments: the type of event to listen for and the function to be called when the event is triggered.

Code:

// Using addEventListener to add an event listener to an element

document.getElementById(“my-element”).addEventListener(“click”, function() {

  // Code to be executed when the element is clicked

});

How do you prevent an element from triggering its default event in JavaScript?

Solution:

To prevent an element from triggering its default event in JavaScript, you can use the preventDefault method of the event object. This method cancels the default action of the event, such as following a link or submitting a form.

Code:

// Using preventDefault to prevent an element’s default event

document.getElementById(“my-link”).addEventListener(“click”, function(event) {

  event.preventDefault();

});

How do you stop an event from bubbling up the DOM hierarchy in JavaScript?

Solution:

To stop an event from bubbling up the DOM hierarchy in JavaScript, you can use the stopPropagation method of the event object. This method prevents the event from triggering any event listeners on ancestor elements.

Code:

// Using stopPropagation to stop an event from bubbling up the DOM hierarchy

document.getElementById(“my-element”).addEventListener(“click”, function(event) {

  event.stopPropagation();

});

How do you dynamically load a script in JavaScript?

Solution:

To dynamically load a script in JavaScript, you can create a new script element and append it to the document’s head element. You can then set the src attribute of the script element to the URL of the script you want to load.

Code:

// Using createElement and appendChild to dynamically load a script

var scriptElement = document.createElement(“script”);

scriptElement.src = “https://example.com/script.js”;

document.head.appendChild(scriptElement);