Search code examples
javascriptjquerycssclone

jQuery: using .css on a cloned element to obtain a specific css property?


I am trying to obtain the font-size currently applied to a cloned element, but when I use the jQuery .css function, it doesn't retrieve anything.

Is it not possible to use the ".css" function in jQuery to retrieve a specific css property from a cloned element?

The following does not work:

var clonedElement = jQuery('.element').clone();
clonedElement.attr("style", "");
var defaultFontSizeValue = clonedElement.css('font-size');
console.log(defaultFontSizeValue);

Edit 1 The original unfortunately has inline styles that don't allow me to get the overridden font-size property for that element that is applied via a class. This is why I am trying to retrieve that original value by removing the inline styles in the clone.


Solution

  • Your problem is that the cloned element is not "attached" to your dom, and therefore there is no style definition to this element (based on css that are not inline).

    What you can do is append the cloned element to the body (after setting display: hidden, if you want), and then check the font-size:

    $(function() {
      console.log($('.c1').css('fontSize'));
      c1 = $('.c1').clone();
      console.log(c1.css('fontSize'));
      
      c1.css('display', 'none');
      $('body').append(c1)
      console.log(c1.css('fontSize'));
    });
    .c1 {
      font-size: 12px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="c1">asd</div>