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.
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.
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.
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 ;
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.
精彩评论