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?
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.
You can't. A pseudo element is not in the DOM so can't be selected by JS.
jQuery after() Method The after() method inserts specified content after the selected elements.
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.
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.
use insertAfter():
$("<div id='xxx'></div>").insertAfter("#somediv > ul").append($("#someotherdiv").clone())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With