Domanda

I tried looking at this post which has an almost identical title but despite trying the answer that appeared suitable, my code still isn't working.

I'm creating an element outside of the dom like this:

var e = $('<div class="alert"><div class="messageBox"><h1>'+type+'</h1><p class="message">'+message+'</p></div></div>');

On the next line, I'm attempting to manipulate it.

$('.alert',e).width($(window).width()).height($(window).height());

As you can see, I tried to define the context for the selector (the suggestion I saw in the other post) but it isn't working. Can someone point out to me what I've done wrong?

È stato utile?

Soluzione

The .alert div is already at the root of your e variable DOM contents, so no need to use context parameter (that will cause to find inside your .alert div for another .alert div, which won't find anything) so just do like this:

e.width($(window).width()).height($(window).height());

If you were to assign some property to your .messageBox div, then it would work to use the context parameter like you did:

 //this will work as .messageBox is inside your root element(.alert)
 $('.messageBox',e).width(...);

Altri suggerimenti

$('.alert',e) is equivalent to e.find('.alert') which returns nothing because e is .alert

Just use:

e.width($(window).width()).height($(window).height());
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top