Skip to content

Latest commit

 

History

History
326 lines (224 loc) · 11.4 KB

DOM Injection 5c4ced1b454b44969d866180e0f98821.md

File metadata and controls

326 lines (224 loc) · 11.4 KB

DOM Injection

Detecting when the DOM is ready

Detecting when the DOM is ready in JavaScript is an essential step before manipulating the document's elements dynamically. One of the most common ways to detect when the DOM is ready is to use the DOMContentLoaded event. This event fires when the browser has finished parsing the HTML and constructing the DOM tree. Here's an example of how you can use it:

document.addEventListener('DOMContentLoaded', function() {
  // Your code to manipulate the DOM goes here
});

Alternatively, you can use the window.onload event to detect when the entire page, including images and stylesheets, has finished loading. However, keep in mind that using window.onload may cause delays in the page loading, so it's not always the best choice.

window.onload = function() {
  // Your code to manipulate the DOM goes here
};

Finally, if you're using a JavaScript library like jQuery, you can use its ready() method to detect when the DOM is ready:

$(document).ready(function() {
  // Your code to manipulate the DOM goes here
});

Whichever method you choose, make sure to place your code inside the callback function to ensure that the DOM is ready before attempting to manipulate it.

Project:

  • Try out the code below & feel free to change the values.
  • index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>DOM Ready Example</title>
  </head>
  <body>
    <h1>DOM Ready Example</h1>
    <p id="message">This text will be replaced by JavaScript code.</p>
    <script src="index.js"></script>
  </body>
</html>
  • app.js
document.addEventListener('DOMContentLoaded', function() {
  // Your code to manipulate the DOM goes here
  const message = document.getElementById('message');
  message.textContent = 'Hello, World!';
});

In this example, the HTML code contains a <p> element with the id message, which will be replaced by JavaScript code when the DOM is ready.

The DOMContentLoaded event is used to detect when the DOM is ready, and the code to manipulate the DOM is contained inside the callback function. In this case, the code selects the <p> element with the id message using the getElementById() method and sets its textContent property to 'Hello, World!'. When the page is loaded, the text of the <p> element will be replaced by the new message.

Note that this example does not use jQuery, but the same principles apply if you were using it. You would simply need to include the jQuery library and replace the document.addEventListener('DOMContentLoaded', function() {...}); code with $(document).ready(function() {...});

Adding text and HTML to an element

You can add text and HTML to an element in several ways using JavaScript. Here are some examples:

  • Using the innerHTML property: The innerHTML property sets or returns the HTML content (inner HTML) of an element. You can use it to add text or HTML to an element:
// Get the element
const element = document.getElementById("my-element");

// Add text to the element
element.innerHTML = "Hello World!";

// Add HTML to the element
element.innerHTML = "<h1>Hello World!</h1>";
  • Using the textContent property: The textContent property sets or returns the text content of an element:
// Get the element
const element = document.getElementById("my-element");

// Add text to the element
element.textContent = "Hello World!";
  • Using the createElement and appendChild methods: You can create a new element and append it to an existing element:
// Get the element
const parent = document.getElementById("parent-element");

// Create a new element
const newElement = document.createElement("p");

// Set the text content
newElement.textContent = "Hello World!";

// Append the new element to the parent element
parent.appendChild(newElement);
  • Using the insertAdjacentHTML method: You can insert HTML at a specified position relative to the element:
// Get the element
const element = document.getElementById("my-element");

// Insert HTML after the element
element.insertAdjacentHTML("afterend", "<p>Hello World!</p>");

// Insert HTML before the element
element.insertAdjacentHTML("beforebegin", "<p>Hello World!</p>");

// Insert HTML at the beginning of the element
element.insertAdjacentHTML("afterbegin", "<p>Hello World!</p>");

// Insert HTML at the end of the element
element.insertAdjacentHTML("beforeend", "<p>Hello World!</p>");

Project:

  • Try out the code below & feel free to change the values.
  • index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Adding Text and HTML to an Element with JavaScript</title>
  </head>
  <body>
    <div id="my-element"></div>
    <div id="parent-element"></div>
	  <script src="app.js"></script>
  </body>
</html>
  • app.js
 // Using the innerHTML property
      const element = document.getElementById("my-element");
      element.innerHTML = "Hello World!";
      element.innerHTML = "<h1>Hello World!</h1>";

      // Using the textContent property
      const element2 = document.getElementById("my-element");
      element2.textContent = "Hello World!";

      // Using the createElement and appendChild methods
      const parent = document.getElementById("parent-element");
      const newElement = document.createElement("p");
      newElement.textContent = "Hello World!";
      parent.appendChild(newElement);

      // Using the insertAdjacentHTML method
      const element3 = document.getElementById("my-element");
      element3.insertAdjacentHTML("afterbegin", "<h1>Hello World!</h1>");
      element3.insertAdjacentHTML("beforeend", "<p>Hello World!</p>");

In this example, we first create a div element with an id of my-element and another div element with an id of parent-element. We then use JavaScript to add text and HTML to the my-element div element using the innerHTML and textContent properties, as well as the insertAdjacentHTML method. We also create a new p element with the text "Hello World!" and append it to the parent-element div element using the createElement and appendChild methods.

Creating new elements

In JavaScript, it is not possible to create new elements in the same way that you can create new objects or functions. However, you can dynamically create and add elements to the DOM (Document Object Model) using JavaScript.

Here is an example of how you can create a new element (in this case, a paragraph element) using JavaScript and add it to the DOM:

// create a new paragraph element
var newParagraph = document.createElement('p');

// set the text content of the paragraph element
newParagraph.textContent = 'This is a new paragraph created with JavaScript!';

// get a reference to the parent element where you want to add the new paragraph
var parentElement = document.getElementById('myParentElement');

// add the new paragraph to the parent element
parentElement.appendChild(newParagraph);

In this example, document.createElement() creates a new paragraph element, newParagraph.textContent sets the text content of the element, document.getElementById() gets a reference to the parent element where we want to add the new paragraph, and parentElement.appendChild() adds the new paragraph to the parent element.

Project:

  • Try out the code below & feel free to change the values.
  • index.html
<!DOCTYPE html>
<html>
<head>
  <title>Creating Elements with JavaScript</title>
</head>
<body>
  <div id="myParentElement">
    <h1>My Parent Element</h1>
    <p>Existing paragraph element.</p>
  </div>

  <script src="app.js"></script>
</body>
</html>
  • app.js
// create a new paragraph element
var newParagraph = document.createElement('p');

// set the text content of the paragraph element
newParagraph.textContent = 'This is a new paragraph created with JavaScript!';

// get a reference to the parent element where you want to add the new paragraph
var parentElement = document.getElementById('myParentElement');

// add the new paragraph to the parent element
parentElement.appendChild(newParagraph);

In this example, the JavaScript code creates a new paragraph element using document.createElement(), sets the text content of the paragraph element using newParagraph.textContent, gets a reference to the parent element where we want to add the new paragraph using document.getElementById(), and adds the new paragraph to the parent element using parentElement.appendChild(). When the HTML page loads, the JavaScript code is executed and adds the new paragraph to the parent element.

Removing elements from the DOM

Removing elements from the DOM (Document Object Model) can be done using the removeChild() method or the remove() method. Here are examples of both methods:

  • Using removeChild() method: You can remove a child element from a parent element using the removeChild() method. Here is an example:
var parentElement = document.getElementById('myParentElement');
var childElement = document.getElementById('myChildElement');
parentElement.removeChild(childElement);

In this example, parentElement is the parent element and childElement is the child element that you want to remove.

  • Using remove() method: You can also remove an element using the remove() method, which is a newer method and is supported in modern browsers. Here is an example:
var childElement = document.getElementById('myChildElement');
childElement.remove();

This will remove the myChildElement from the DOM.

In both cases, the element is removed from the DOM, but there is a slight difference between the two methods. The removeChild() method requires you to reference the parent element, while the remove() method can be called directly on the element that you want to remove.

It is also worth noting that removing an element from the DOM will also remove any event listeners or data associated with that element, so you should be careful when removing elements from the DOM.

Project:

  • Try out the code below & feel free to change the values.
  • index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Removing an element from the DOM</title>
  </head>
  <body>
    <div id="parent">
      <p id="child">This is the child element.</p>
      <button id="removeBtn">Remove Element</button>
    </div>
    
    <script src="app.js"></script>
  </body>
</html>
  • app.js
// get references to the parent element and the button
var parentElement = document.getElementById('parent');
var removeBtn = document.getElementById('removeBtn');

// add event listener to the button
removeBtn.addEventListener('click', function() {
  // get reference to the child element
  var childElement = document.getElementById('child');
  
  // remove the child element
  parentElement.removeChild(childElement);
});

In this example, we use the getElementById() method to get references to the parent element and the button in our JavaScript code. We then add an event listener to the button using the addEventListener() method. The event listener function gets a reference to the child element using getElementById(), and then removes it from the parent element using the removeChild() method.

When the user clicks the "Remove Element" button, the child element is removed from the DOM.