Member Avatar
ziyaddinsadigov

Hi, I want to add element after an element with loop. For example, I have 10 paragraph elements and I want to add div element after each paragraph element. How can I do it?

You can use insertAfter() Jquery method

     $("<div>Hello world!</div>").insertAfter("p");
Member Avatar
ziyaddinsadigov

Thanks, but I want for JavaScript code. What is the alternative method?

A codesnippet for this.

Here first get the parentNode of paragraph element called parent element.Then check if parent's last child is paragraph element.If yes then appenChild(new div element) to parent.Else call insertAfter()

//create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
//target is what you want it to go after. Look for this elements parent.
    var parent = targetElement.parentNode; 
//if the parents lastchild is the targetElement...
        if(parent.lastchild == targetElement) {
//add the newElement after the target element.
            parent.appendChild(newElement);
        } else {
    // else the target has siblings, insert the new element between the target and it's next sibling.
            parent.insertAfter(newElement, targetElement.nextSibling);
        }
    }

I have not checked this but it must work.

Member Avatar
ziyaddinsadigov

ok, thanks! I will try it. And my code has for method for looping all paragraph elements. I will try it inside for method.