Using jQuery to retrieve HTML element's css properties hasn't been as effective as desired. To test this issue, the following experiment was conducted:
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;
The results of the test variables are as follows:
testZero: 0px / ""
testOne: 50% / 50%
testTwo: 670px / 50%
testThree: 670px / 50%
The outcomes revealed:
- testZero: The jQuery version displays 0px, while JS version shows an empty string for unset rules.
- testOne: Both versions perform correctly once the rule is set.
- testTwo: The JS version works accurately, but after appending the div element, jQuery only provides pixel values.
- testThree: Similar behavior occurs when re-selecting the element.
The key question remains: Is there a method to maintain consistent units with the jQuery version post-appending the element?
For instance:
$(element).css("width", "50%"); //Rule is set
container.appendChild(element); //Element is appended
var width = $(element).css("width"); //Desired result is "50%" instead of "xxpx"