Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get real width of elements with jQuery

I am writing a validator for "visual correctness" of html files. The goal is to detect too wide elements.

Here is a demo of my problem.

The dotted red line is an indicator of the max width of the document (200px in this example). The first paragraph is fine, but the second is too wide. Nevertheless, all of the following commands still return "200px" as the width:

// all return 200, but the value should be larger   
$('#two').width();
$('#two').outerWidth();
$('#two').prop('clientWidth');

Please see the Fiddle for more details.

How can i detect such oversized elements?

Updated question: Better to ask, how can i detect text that exceeds the borders of their parent elements?

Updated requirement: I am not allowed to change anything in the source HTML or CSS. But i can do anything i want with jQuery to modify the document, so that i can detect those too wide elements.

like image 355
Alp Avatar asked Apr 23 '12 08:04

Alp


People also ask

How to get width of element using jQuery?

jQuery width() Method The width() method sets or returns the width of the selected elements. When this method is used to return width, it returns the width of the FIRST matched element. When this method is used to set width, it sets the width of ALL matched elements.

How can get image width and height in jQuery?

width(); alert(imageWidth); var imageHeight = Imgsize. height();

What does size () method of jQuery returns?

The size() method returns the number of elements matched by the jQuery selector.


2 Answers

As others have said, temporarily wrap the text node in an inline element.

var two = document.getElementById('two'),
    text = two.firstChild,
    wrapper = document.createElement('span');

// wrap it up
wrapper.appendChild(text);
two.appendChild(wrapper);

// better than bad, it's good.
console.log(wrapper.offsetWidth);

// put it back the way it was.
two.removeChild(wrapper);
two.appendChild(text);

http://jsfiddle.net/vv68y/12/

Here is a getInnerWidth function that should be useful to you. Pass it an element and it will handle the wrapping and unwrapping.

function getInnerWidth(element) {

    var wrapper = document.createElement('span'),
        result;

    while (element.firstChild) {
        wrapper.appendChild(element.firstChild);
    }

    element.appendChild(wrapper);

    result = wrapper.offsetWidth;

    element.removeChild(wrapper);

    while (wrapper.firstChild) {
        element.appendChild(wrapper.firstChild);
    }

    return result;

}

http://jsfiddle.net/vv68y/13/

like image 83
Dagg Nabbit Avatar answered Sep 30 '22 22:09

Dagg Nabbit


scrollWidth will do it:

$("#two").get()[0].scrollWidth or getElementById("two").scrollWidth

this outputs 212px, the real width you are looking for.

like image 44
NateQ Avatar answered Sep 30 '22 22:09

NateQ