clarkk
clarkk

Reputation: 27679

how to get an element before its added to the DOM?

How can you get an element before its added to the DOM (before append())

$('#enclosure_balance'+id).css({background:'red'})

Upvotes: 2

Views: 515

Answers (3)

Šime Vidas
Šime Vidas

Reputation: 185883

I suppose the element is in a jQuery object.

Do either

obj.filter( selector )

or

obj.find( selector )

where obj is the jQuery object which contains your element, and selector is the selector which is supposed to match your element.

filter works if your element is one of the elements of the jQuery object. find works when your jQuery object contains one or more elements which in turn have ancestors, and your element is among those ancestors.

Upvotes: 1

gilly3
gilly3

Reputation: 91467

The answer is in the question. You already have a reference to the element, else you couldn't call append. If you have this:

$("#parent").append("<div />");

Modify it to this:

var child = $("<div />");
child.css({ background: "red" });
$("#parent").append(child);

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186562

As far as I know, the only way is by reference if you control or have access to the construction of it.

var s = $('<div id="stupid"/>')

Reference the variable / property which contains it. Since it hasn't been appended it's not accessible via the DOM methods.

If you want the element to be visibly hidden just append it to a container element that has offsetting css values ( eg position absolute, top -999em, left -999em )

EDIT: There are also document fragments: http://ejohn.org/blog/dom-documentfragments/#postcomment but since they're not in the document itself, you can't reference the elements inside with document.getElementById and such.

Upvotes: 3

Related Questions