0

Scenario: You have a div with some text, this div has no css width, no jquery width, no width attribute assigned to it in any way. However it has a width due to the content that is inside it, this is undefined, reports as "null" in jQuery. My question is: is there any way to retireve the width of this div?

8
  • 3
    @ThomasReggi: my experiments suggest that such a div does in fact report a width when using jQuery. here's a simple example at jsFiddle. Maybe there is something special about your scenario -- can you elaborate? Commented Dec 4, 2010 at 20:22
  • @Thomas , are you adding that div dynamically ?? post your html , jquery .width you definetly get you the width. Commented Dec 4, 2010 at 20:24
  • @Thomas post your complete html or make an example at jsfiddle so that we can fix your problem or we can learn a new thing....if this is a different case. Commented Dec 4, 2010 at 20:35
  • I believe an unstyled div doesn't get it's width from the content within it but will get it's height from that. So I believe the default width of a div is the width of it's container, maybe you could grab that? Commented Dec 4, 2010 at 20:40
  • it works thanks (missed the class dot) ty! Commented Dec 4, 2010 at 20:40

3 Answers 3

3

$(element).width() should give you the actual width. With $(element).outerWidth(includeMargin) you can even get the width including padding, border, and, if desired, the margin.

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

Comments

1

with jquery you can do below

$('#id').width()

Comments

0

You can use the offsetWidth like this:

element.offsetWidth

or with a ref in React

elementRef.current.offsetWidth

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.