dev.e.loper
dev.e.loper

Reputation: 36064

Creating html element with jquery, how can I get element's width?

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

Answers (4)

Josiah Ruddell
Josiah Ruddell

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

mahioo
mahioo

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

Psytronic
Psytronic

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

John Strickler
John Strickler

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

Related Questions