usmanali
usmanali

Reputation: 2036

Is there any alternative to jQuery .after() function

I am trying to convert my jQuery script into javascript. I have a problem there..

I have a script that creates a node

var new_node = document.createElement("div");
      new_node.className="tooltip";
      new_node.innerHTML = html;
      alert(new_node.className);

When i do this

jQuery(link).after(new_node);

It works fine. But I want to do it javascript way. I have tried using appendChild function but it gives some strange results.

Please help me out with this.

Upvotes: 3

Views: 7795

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074545

You're comparing jQuery's after with appendChild, but they do very different things. after puts the element after the reference element, appendChild puts it inside it.

You probably want insertBefore (with the reference node being link's nextSibling).

So:

var link = /* ... get the `a` element from somewhere ... */;
var new_node = document.createElement("div");
new_node.className="tooltip";
new_node.innerHTML = html;
link.parentNode.insertBefore(new_node, link.nextSibling);

If link is the last thing in its parent, that's fine; link.nextSibling will be null and insertBefore accepts null as the reference node (it means "insert at the end").

Upvotes: 12

Robusto
Robusto

Reputation: 31883

Assuming you already have a node instantiated as link, you could do what you want this way in plain Javascript:

link.parentNode.appendChild(new_node);

The link node would have to be the last node in its container. Otherwise you would have to find link's nextSibling and use insertBefore to put new_node in its proper place.

Upvotes: 0

mdm
mdm

Reputation: 12630

jQuery(link).append(new_node);

Upvotes: -2

Related Questions