开发者

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

开发者 https://www.devze.com 2023-04-10 04:05 出处:网络
How can you get an ele开发者_如何学JAVAment before its added to the DOM (before append()) $(\'#enclosure_balance\'+id).css({background:\'red\'})

How can you get an ele开发者_如何学JAVAment before its added to the DOM (before append())

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


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.


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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消