Give this a try:
$("#cevre h2").each(function() {
$(this).appendTo($(this).next("p"));
});
This code utilizes the .each()
function to loop through all the h2
elements. Inside the loop, $(this)
represents each individual h2
element.
Here is a working example demonstrating how it works.
Important: When using appendTo
, keep in mind that it moves the element. If you want to maintain the original and move a copy instead, consider the following approach:
$("#cevre h2").each(function() {
$(this).clone().insertAfter($(this).next("p"));
});
This time, we are using .clone()
to duplicate the h2
element before inserting it using .insertAfter()
.
You can see a working example here with this modification.
Additional tip: It's not valid HTML to have duplicate id
attributes on a single page. Consider changing <div id="cevre">
to <div class="cevre">
and adjust your jQuery selector accordingly to $(".cevre h2")
.
Another suggestion: To improve performance, cache jQuery objects if they are used repeatedly:
$(".cevre h2").each(function() {
var $this = $(this);
$this.clone().insertAfter($this.next("p"));
});