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.
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.
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.
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)
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With