Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a DIV into another DIV with JQuery?

Tags:

jquery

How do I add a custom DIV to an already existing DIV with JQuery?

<div id="old-block"><div id="new-block">Lorem Ipsum</div></div>

Thanks in advance.

like image 209
DezoLord Avatar asked Aug 14 '15 11:08

DezoLord


People also ask

How append a div in another div using jQuery?

First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the appendTo() method to copy the element as its child.

How do I append a div after another div?

To insert element in document after div element using JavaScript, get reference to the div element; call after() method on this div element; and pass the element to insert, as argument to after() method.

What is insertAfter in jQuery?

The insertAfter() method is an inbuilt method in jQuery that is used to insert some HTML content after a specified element. The HTML content will be inserted after each occurrence of the specified element. Syntax: $(content).insertAfter(target)

How do I insert a div?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')


1 Answers

There are many ways to insert a div inside another div.

We can use .append() to do it like this:

$('#old-block').append('<div id="new-block-2"></div>');

We can also use .appendTo() like this:

$('<div id="new-block-2"></div>').appendTo('#old-block');

Maybe we feel not so fancy today and want to use plain JavaScript:

document.getElementById('old-block').appendChild('div');

document.getElementById('old-block').innerHTML += '<div id="new-block-2"></div>';

You could also try parsing the HTML with RegEx.

like image 166
Timo Avatar answered Oct 22 '22 09:10

Timo