2
Contributors
4
Replies
20
Views
4 Years
Discussion Span
Last Post by ziyaddinsadigov
0

You can use insertAfter() Jquery method

     $("<div>Hello world!</div>").insertAfter("p");
0

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

0

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.

Edited by IIM

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.