programming code

How to insert a new div with a class immediately after a specific div using jQuery

You might sometimes to add a new div with a class immediately after a specific div. It will be easy to make it done if you are able to edit the html codes directly. However, if you have no access to source code, you might use jQuery. There are several methods:

var myClass = "thisIsMyClass";
var div = $("<div></div>").addClass(myClass);
$(this).after(div);

For example, you can use the above script as follows:

var myClass = "thisIsMyClass";
var div = $("<div>Text</div>").addClass(myClass);
$(".current").after(div);

Demo – jsfiddle. Of course, you can use before() instead of after() if you want the new div immediately before the existing div as follows:

var myClass = “thisIsMyClass”;
var div = $(“<div>Text</div>”).addClass(myClass);
$(“.current”).before(div);
// jsfiddle

Or, the following scripts can also be considered:

$('<div>Mr. Kim</div>',{ class : 'sample'}).appendTo(".current");

– OR –

$("<div>Mr. Kim</div>").insertAfter(".current").addClass(myClass);

You can check the working demos: sample 1sample 2.

Please feel free to leave a Comment (). Have a great day.