What is the method to fetch CSS properties in relative units like percentages and ems using the .css() function with the selector "$("selector")"?

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"

Answer №1

Behold, a function of my own making:

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

This function will fetch the value of the specified attribute from the inline style or fall back to the computed value if not found.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for decoding Dropbox Public folder images in HTML

Is there a way to read and display all images from a Dropbox public folder using jQuery loop? I have successfully displayed a single image like this: Simple Image "" But how can I access all images in the Dropbox public folder if their number is unknown ...

What exactly does the jquery ajax success callback cover?

Is the value of testvar in function AjaxRequest going to increase on success? function AjaxRequest(){ var testvar = 0; for(i=0;i<d.length;i++){ $.ajax({ success: function(a){ testvar++; } ...

Generating a unique user ID similar to Zerodha's user ID using Node.js/JavaScript

For a project I'm working on, I need to create random and unique User IDs. I came across Zerodha's user IDs which are easy to remember. In Zerodha user IDs: The first two characters are always letters followed by four numbers. I want to generat ...

Adjusting the space between div elements when resizing the window

I am seeking guidance on how to ensure that the text boxes (div) on my page adjust themselves properly when the size of the page is shrunk. Currently, the text boxes tend to overlap when the screen size is smaller, which is not desirable. I need the boxes ...

What is the proper way to assign a class name to an animation state in Angular 2/4?

I am currently working with Angular Animations using version 4.1.3 Check out the code snippet below: @Component({ selector : 'my-fader', animations: [ trigger('visibilityChanged', [ state('true' , style({ opaci ...

The screen should smoothly slide upwards when the keyboard pops up, ensuring the footer remains und

Hello! I am currently in the process of developing a mobile app using HTML, CSS, Bootstrap, and JavaScript. I have encountered a slight issue where the keyboard does not automatically pop up and move the screen up when the user taps on the textbox in the f ...

State change shows the previous and current values simultaneously

I've been working on updating the values of initUsers on the DOM. The initial state values work fine, but when I try to update initUsers, it displays different values than expected. Essentially, entriesNum receives a number as an event and changes th ...

Incorporating a scrollbar into a CSS content accordion for enhanced user experience

Currently, I am exploring a tutorial for coding a content accordion which can be found here: I am wondering about the possibility of adding endless content to each section while incorporating a scroll bar. Any suggestions on how to achieve this? Apprecia ...

Bootstrap CSS allows for easy closing of modals

Having trouble with the Twitter Bootstrap CSS causing my animation to open with a fade and immediately close. Not sure why this is happening, can anyone provide assistance? Update: Turns out, the bootstrap.css file already has Modals implemented. Using bo ...

Compose an email without the need to access the website

Is there a way to send email reminders to users without having to load the website pages? In the reminder section, users can select a date for their reminder and an email will be automatically sent to them on that date without requiring them to access the ...

What is the best way to transfer a value to v-model using emit?

I'm having trouble passing the selected value from a select field to v-model. Currently, the code only seems to work with a v-text-field. <script> export default { name: 'FormSelect', props: { model ...

Setting up event listeners from a string array (using PIXI.js)

Hey there! I've encountered a bit of an interesting challenge that could easily be resolved by duplicating the code, but where's the fun in that? This project is more of an experiment for me, just to prove that I can do it. However, the idea has ...

Adding a unique header to an Ajax CORS request can be achieved by following a few

Searching for a way to include a custom header for Ajax CORS request? Look no further! My server is PHP Lumen and the proxy server is Nginx. The file bootstrap/app.php holds my project configuration details https://i.sstatic.net/zxM7G.png I've come ...

Each Vue instance on the page has its own isolated Vuex store

I have a situation where I am creating multiple Vue apps on the same page: import Vue from "vue"; import App from "./App.vue"; import useStore from "./store"; const arr = [1, 2]; for (const index of arr) { const store = use ...

Switching camera controls in Three.js from First Person to Orbit mode (and vice versa) can be easily

Transitioning between Three.js FirstPerson controls and Orbit controls can be seamless, but there seems to be an issue when switching from First Person to Orbit where the display gets stuck in a 'mousedown' mode. Is there a way to easily go back ...

Having trouble interpreting the Json response from a jQuery Ajax POST request

When I receive a JSON from a REST API via Ajax, if I print the result to the console and then save it into a string variable (jsonInput) `JSON.parse` works without any issues. However, when I directly use the data from the Ajax call, it returns as undefi ...

Discover the Google Chrome Extension that allows you to easily obtain JSON data from your

Here is the structure I have: And below is my manifest.json: { "manifest_version": 2, "name": "Doktor-MD", "description": "Share links on Doktor-MD through the browser.", "version": "1.0", "permissions": [ "http://www.google.com/" ], "browser_action": ...

JavaScript code that displays items in a shopping cart

I've set up the HTML and JS functionality for the cart, but I'm facing an issue where the JS doesn't render the cart items when the shop item is clicked. The styling in my HTML is done using Tailwind. If anyone could provide some assistance ...

What methods can I implement to prevent my boxes from becoming stretched out?

How can I prevent this box from stretching too much? Here is the code snippet along with the output: CSS: .social { padding-left: 1000px; border: 5px inset black; margin: 4px; width: 100px; } HTML: <div class="social"> <p& ...

Even with e.preventDefault, the anchor link still opens in a new tab on the browser

I am dealing with an ajax call that triggers a REST API to return a list of all names, as well as another REST API that matches those names. For instance: /list returns: list1, list2, list3 and /api/list1.json returns: JSON data for list1.. Currently, ...