tags:

views:

44

answers:

4

I'm creating html element using jQuery like so:

    var newListItem = $("<li>" + variableName + "</li>");

    var widthOfNewItem = newListItem.width(); //<-- will return 0

How can I find this new elements width? I'm trying to call newListItem.width() but that returns 0.

+1  A: 

You haven't placed the element into the DOM yet. You've simply created an element and stored it to a variable. Append it to something such as:

$('ul').append(newListItem);

Then check its width.

John Strickler
yeah then i have to check width of that 'ul'. thanks.
dev.e.loper
+1  A: 

Why would it have a width if it doesn't exist anywhere on the page? It's width will be defined by it's container size and css. So far you haven't appended it to anything, so it's just floating around in JS limbo.

Psytronic
correct. i had to check its container to find out the width.
dev.e.loper
A: 

you can get The width of an element by using offsetWidth ; also you can get the height of an element by using offsetWidth ; for example :

var obj = document.getElementById('Your_Element_ID') ;
var width = obj.offsetWidth ;
var height = obj.offsetHeight ;
mahioo
A: 

If you need the width before it shows you can append it to a container with visibility:hidden. This allows you to check the width, without showing the element.

Josiah Ruddell