Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Getting the width of a text node

A bit of (JS-modified) HTML might look like this:

<div style="width: 50px;">1,234,567</div>

How do I detect if the text node is wider than the container?

Upvotes: 6

Views: 5963

Answers (1)

Matt Ball
Matt Ball

Reputation: 359816

As inspired by How to detect overflow in div element?:

<!-- Overflowing -->
<div style="width: 50px;">1,234,567</div>

<!-- Not overflowing -->
<div>1,234,567</div>

JavaScript (no jQuery) to detect:

var divs = document.getElementsByTagName('div');
var i, div, overflowing;

for (i=0; i<divs.length; i++) {
    div = divs[i];
    overflowing = div.offsetWidth < div.scrollWidth;
    console.log(overflowing);
}​

http://jsfiddle.net/mattball/pYj5P/

Upvotes: 7

Related Questions