Skip to content
the poor coder

insertadjacenthtml javascript

Poor Man
Published
Reading time
1 min read
On this page

InsertAdjacentHTML in JavaScript#

InsertAdjacentHTML is a method in JavaScript that allows you to insert HTML content at a specified position relative to an element. It is a powerful tool that can help you dynamically change the structure of your web page without reloading it.

Syntax#

The syntax for using the InsertAdjacentHTML() method is as follows:

Text
element.insertAdjacentHTML(position, text);

Parameters:

  • position: The position relative to the element where the HTML content will be inserted. It can be one of the following values:
  • 'beforebegin': Inserts the HTML content immediately before the element.
  • 'afterbegin': Inserts the HTML content inside the element, before its first child.
  • 'beforeend': Inserts the HTML content inside the element, after its last child.
  • 'afterend': Inserts the HTML content immediately after the element.
  • text: The HTML content that will be inserted.

Example#

Let's say we have an HTML div with an id of "myDiv". We can use the InsertAdjacentHTML method to add some content to it dynamically:

Text
// Get the div element
var div = document.getElementById("myDiv");

// Insert HTML content before the div
div.insertAdjacentHTML("beforebegin", "This is some text before the div!");

// Insert HTML content inside the div
div.insertAdjacentHTML("afterbegin", "InsertAdjacentHTML ExampleThis is some text inside the div!");

// Insert HTML content after the div
div.insertAdjacentHTML("afterend", "This is some text after the div!");

This will add a paragraph of text before the div, an h3 heading and another paragraph of text inside the div, and a final paragraph of text after the div.

It's important to note that while InsertAdjacentHTML is a powerful method, it can also be a security risk if not used properly. Always validate any user input before inserting it into your web page to prevent XSS attacks.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC