views:

238

answers:

3

I have the following code

var input = $('#el_id');
wrapper = $(document.createElement('div'));
wrapper.addClass('small');
wrapper.css('width',200);
input.wrap(wrapper);

alert(input.children().length)

I get 0 for the children length. What I want is:

<div class="small" style="width: 200px;">
     <input type="text" id="el_id" />
</div>

But I want the small div to be dynamically generated. Any idea why this isn't working?

UPDATE

It turns out my issue lies on another line of code. I want to assign the wrapper to a variable after I wrap and:

block = input.wrap("<div class='"+container_class+"' style='width: "+wrap_width+"px;'></div>");

does not work. It returns the input which makes sense. But how can I return the wrapper?

Thanks!

A: 

From the documentation, it appears that wrap() only accepts a DOM element or a string. You are passing it a jQuery object, which may not work. I'd try this:

$('#el_id').wrap('<div class="small" style="width: 200px;"></div>');
Peter
+2  A: 

I believe you are doing it right.

You just need to save the results of the wrap function to a variable:

Edit: Updated the code to get parent():

var wrapped = input.wrap(wrapper).parent();
alert(wrapped.children().length);
Jeff Meatball Yang
the thing screwing me up is "wrapped" in your example is not returning the same results as if i were to just grab the wrapper element with $('#wrapper_id'). do you know why that is?
Tony
Whoops - I thought wrap() returned the new context - sorry about that. You COULD just do: input.wrap("..."); var wrapped = input.parent();
Jeff Meatball Yang
A: 

Simple. You are trying to wrap with a jquery object and not a dom object which is what the wrap() function expects.

abjbhat