Reputation: 36064
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.
Upvotes: 1
Views: 1976
Reputation: 29841
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.
Upvotes: 0
Reputation: 1
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 ;
Upvotes: 0
Reputation: 6113
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.
Upvotes: 3
Reputation: 25421
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.
Upvotes: 2