user1626840 user1626840 - 5 months ago 12
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>';
$(this).html(html_calc);
var width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};


I am calling it as follows:

$(".checkbox-inline-tooltip").each(function () {
$(this).css({
"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.

Answer

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(){
    $(this).wrapInner('<span>');
    var width = $(this).find('span:first').width();
    $(this).find('span:first').contents().unwrap();
    return width;
};
Comments