user1626840 user1626840 - 1 year ago 82
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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download