user1626840 user1626840 - 9 months ago 37
Javascript Question

Calculating text width without losing DOM attributes

When trying to calculate text width using jquery, the "checked" attribute of the radio input is lost.
I am using the following code:

$.fn.textWidth = function(){
var html_org = $(this).html();
var html_calc = '<span>' + html_org + '</span>';
var width = $(this).find('span:first').width();
return width;

I am calling it as follows:

$(".checkbox-inline-tooltip").each(function () {
"position": "relative",
"float": "left",
"top": "-32px",
"left": $(this).prev('label').textWidth() + 30 + "px"

The 'prev' label has a radio input. The attribute "checked" is lost after the textWidth() is called, which results in unchecking of the radio.


Try element wrapInner() and unwrap(). Getting the innerHTML, doesn't get the properties such as checked, disabled which are set dynamically in the input element.

$.fn.textWidth = function(){
    var width = $(this).find('span:first').width();
    return width;