Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

possible to use jQuery on elements outside the document?

Working with some legacy architecture and because of the nature of the initialization sequence I need to wrap an element before it's been added to the document. Say I have the following:

<div id="containerX">
   <div id="myNode"></div>
</div>

And I need to wrap "myNode" before it's added to the DOM. Do jQuery selectors even work in this context? If so, how can I make that happen? I've tried passing in the element like so:

(Corrected some typos here referred to in some answers below):

$(this.element).wrap('<div id="'+ "myWrapper_" + this.id + '"></div>');

with no luck. I'm assuming that the usual syntax for selectors won't work since the nodes are outside the document. The closest thing I've found was this post here: Manipulate DOM elements before adding them to the document but the difference between my situation and his is I don't have strings, I have elements created with document.createElement that have not been appended.

Can anyone point me in the right direction or is this even possible?

Thanks

like image 237
Shane Avatar asked Nov 14 '11 12:11

Shane


People also ask

How to append an element as a first child in jQuery?

The . prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).

How to append at the beginning in jQuery?

The prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.

What is jQuery content?

jQuery contents() Method The contents() method returns all direct children, including text and comment nodes, of the selected element. A text node is the actual text displayed by an element. This method is similar to the children() method, except that it returns text and comment nodes as well.


1 Answers

You can use Jquery on other elements as as well, and I've more than once used it to parse a response from an AJAX request.

Though I am not sure if your exact request is possible, I think the main problem in your code is the missing < before the div you're trying to wrap around your element.

like image 97
GolezTrol Avatar answered Sep 27 '22 17:09

GolezTrol