Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  86] [ 7]  / answers: 1 / hits: 37466  / 12 Years ago, mon, april 23, 2012, 12:00:00

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.


More From » jquery

 Answers
51

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/


[#86054] Saturday, April 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reed

Total Points: 725
Total Questions: 85
Total Answers: 89

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;