2

I used jQuery to get HTML element's css properties. But it doesn't work as well as I want to. So I made a little test:

var div = document.createElement("DIV");
    div.id = "testdiv";
var testZero = $(div).css("width") + " / " + div.style.width;
   $(div).css("width", "50%");
var testOne = $(div).css("width") + " / " + div.style.width;
    document.getElementById("res").appendChild(div);
var testTwo = $(div).css("width") + " / " + div.style.width;
var testThree = $("#testdiv").css("width") + " / " + document.getElementById("testdiv").style.width;

Values of the test variables:

testZero: 0px / ""
testOne: 50% / 50%
testTwo: 670px / 50%
testThree: 670px / 50%

Results are the following:

  • testZero: jQuery version returns 0px. JS version returns "" (empty string), if the rule hasn't been set.
  • testOne: After the rule has been set, both version works correctly.
  • testTwo: JS version works correctly. But as soon as I append the div element, jQuery version only returns px values.
  • testThree: It's the same with re-selecting the element.

The question is: Is there any way to get the same unit with the jQuery version after I append the element?

For example:

$(element).css("width", "50%"); //I set the rule
container.appendChild(element); //I append the element
var width = $(element).css("width"); //And the result is also "50%" not "xxpx"
Jino Shaji
  • 1,097
  • 14
  • 27
Saphyra
  • 450
  • 3
  • 15
  • Possible duplicate https://stackoverflow.com/questions/4006588/is-it-possible-to-use-jquery-to-get-the-width-of-an-element-in-percent-or-pixels – Niladri Sep 20 '17 at 17:24
  • Possible duplicate of [Is it possible to use jQuery to get the width of an element in percent or pixels, based on what the developer specified with CSS?](https://stackoverflow.com/questions/4006588/is-it-possible-to-use-jquery-to-get-the-width-of-an-element-in-percent-or-pixels) – Justinas Sep 20 '17 at 19:34

1 Answers1

0

I created this function:

function getProperty(element, property){
    return (element.style[property] != "") ? element.style[property] : $(element).css(property);
}

Returns the property value set in style="" attribute, or returns the absolute value, if property has not been set.

Saphyra
  • 450
  • 3
  • 15