admin管理员组

文章数量:1277899

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.

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.

Share Improve this question edited Mar 10, 2017 at 10:45 Mohammad 21.5k16 gold badges56 silver badges84 bronze badges asked Mar 14, 2011 at 11:46 usmanaliusmanali 2,0372 gold badges27 silver badges39 bronze badges 2
  • 1 1) Can we see some more of the code? the generated HTML? the existing HTML? etc.. 2) Why are you switching from jQuery to JS? 3)Please work on improving your accept-rate. This is a munity site, after all. – Dutchie432 Commented Mar 14, 2011 at 11:49
  • 2 Just for the record, jQuery code is JavaScript code. I think what you mean is that you want to get away from using the library. – Pointy Commented Mar 14, 2011 at 11:49
Add a ment  | 

3 Answers 3

Reset to default 12

You're paring 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").

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.

jQuery(link).append(new_node);

本文标签: javascriptIs there any alternative to jQuery after() functionStack Overflow