0

context: I have an ajax request which return data structure with an html key.

I would like to wrap this data with a jQuery object to be able to use API like width / height and modify the data before adding it to the DOM.

> $('<div width="220" height="200"></div>').width()
0

So how could I do to get 220 and then modify it ?

I'm using jquery 1.7.2

Edit:

I'm not from the 90's because I use the wrong tag in my example. My need is to change width and height of an iframe for responsive:

> $('<iframe width="220" height="200"></iframe>').width()
0
1
  • can't you just append it into some hidden element like hidden iframe, then manipulate whatever you want, after that delete that element? Commented Dec 30, 2012 at 15:11

3 Answers 3

2

Elements have no width before they're added to the DOM.

A solution, if you really need to not have it in the DOM, is to add it and then detach it :

var d = $('<div width="220" height="200"></div>');
d.appendTo(document.body);
var w = d.width();
d.detach();

As the screen isn't redrawn until your script ends its task, this operation won't be seen by the user.

But note that without a different style, this won't give you 220. You probably want this :

$('<div style="width:220px;height:200px;"></div>');

Demonstration

Sign up to request clarification or add additional context in comments.

Comments

1
  1. You must be from the 90's, because who uses width and height attributes on a div?
  2. There's no width "before adding it to the DOM".

3.

$('<div width="220" height="200"></div>').attr('width')

Comments

0

Use css:

$('<div></div>').css({ 'width': '220px', 'height': '200px'});

This will set the width and height. Since you are setting it, there really is no need to get the width afterwards, right? But you could if needed with width().

EDIT: Maybe I misunderstood - the question isn't too clear. If you want to get the width of an element then width works, but as mentioned, the element needs to be added to the DOM first.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.