Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JQuery "after" selector

I can't seem to figure out a good way to do this, but it seems like it should be simple. I have an element that I want to append a div to. Then I have another element that I want to clone and shove into that intermediate div. Here's what I was hoping to do:

$("#somediv > ul").after("<div id='xxx'></div>").append($("#someotherdiv").clone());

This seems to be close, but not quite there. The problem with this is that the "append" seems to be operating on the original #somediv > ul selector. This sort of makes sense, but it's not what I wanted. How can I most efficiently select that intermediate div that I added with the after and put my #someotherdiv into it?

like image 524
Chris Farmer Avatar asked Sep 10 '08 18:09

Chris Farmer


People also ask

What is the use of after in jQuery?

after( function ) A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.

How do I target a pseudo element in jQuery?

You can't. A pseudo element is not in the DOM so can't be selected by JS.

Which jQuery will you use if there is a need to insert specified content after a selected element?

jQuery after() Method The after() method inserts specified content after the selected elements.

What is before and after in jQuery?

Definition and UsageThe before() method inserts specified content in front of (before) the selected elements. Tip: To insert content after selected elements, use the after() method.


2 Answers

Go the other way around and use insertAfter().

$("<div id='xxx'></div>")
    .append($("#someotherdiv").clone())
    .insertAfter("#somediv > ul")

Try to add your generated DOM nodes to the document only after finishing your work.

Once the nodes are added to the displayed document, the browser starts listening to any change to refresh the view. Doing all the work before adding the nodes to the displayed document does improve browser performance.

like image 63
Vincent Robert Avatar answered Sep 20 '22 13:09

Vincent Robert


use insertAfter():

$("<div id='xxx'></div>").insertAfter("#somediv > ul").append($("#someotherdiv").clone())
like image 29
Jimmy Avatar answered Sep 19 '22 13:09

Jimmy