3

The common way to do it is to appending the new element to the body and then get the computed css values like in this jQuery script:

    var $body = $('body');
    var $this =  $(this);
    var $text = $this.text();
    if($text=='') $text = $this.val();
    var calc = '<div style="clear:both;display:block;visibility:hidden;"><span style="width:inherit;margin:0;font-family:'  + $this.css('font-family') + ';font-size:'  + $this.css('font-size') + ';font-weight:' + $this.css('font-weight') + '">' + $text + '</span></div>';
    $body.append(calc);
    var width = $body.find('span:last').width();
    $body.find('span:last').parent().remove();
    return width;     

Te question is how to do it without appending it to the DOM to avoid slow re-renderings, this script does it without appending it to the DOM:

    var fakeInputText = '<div style="clear:both;display:block;"><span style="width:inherit;margin:0;font-family:Helvetica Neue, Helvetica, Arial, sans-serif;font-size:22px;font-weight:400"></span></div>';
    var parser = new DOMParser();
    var doc = parser.parseFromString(fakeInputText, "text/html");


    var style = document.defaultView.getComputedStyle(doc.getElementsByTagName("div")[0]); //doc.querySelector("span")
    console.log(style);

And this is what it gets: Chrome console result

1 Answers1

0

You can create a jQuery element without appending it to the DOM.

var $yourCachedElement = $("<div>", { // Create your element
   style: "your styling",
   html: "html code to store inside this element"
}),
widthYouWannGet = $yourCachedElement.width(); // Store element's width into the var