The computed style of a node in Chrome returns as null

In my javascript code, I have the following line:

if(document.defaultView && document.defaultView.getComputedStyle){
    strValue = document.defaultView.getComputedStyle(oElm).getPropertyValue(strCssRule);
} // ...

This code is used to retrieve a CSS value of a node (e.g. strCssRule = 'color'). It works in Firefox but only works on simple examples in Chrome on a static page. When I try to integrate it into my complex application, all fields of the returned CSSStyleDeclaration are null.

The node oElem is selected using jQuery (

oElem = $(my_selector).empty().get(0));
). The main difference between the working example and my application is that the node has not yet been added to the DOM when the computation takes place (the full HTML is still being generated).

I even tried explicitly setting the CSS in the HTML declaration (e.g. my node is

<div style="width:100px;"></div>
), but the CSSStyleDeclaration object remains empty.

Edit: As CBroe mentioned, the issue arises because the element is not linked to the DOM yet. The browser's implementation determines how it handles this scenario. Although Firefox was able to make it work, I will need to find an alternative solution.

Answer №1

If you are familiar with the CSS rule selector and its location in the CSS files, you can easily locate it by searching through the stylesheets. This is how I tackled the problem at hand.

var page, rule, css;
var selector = ".my_selector";
var sheets = document.styleSheets;
for( page = 0; page < sheets.length; page++ ){
    // By excluding this if-statement, you can search through all available stylesheets on the page
    if( sheets[page].href.match(/.*\/filename\.css$/) ){
        for( rule = 0; rule < sheets[page].length; rule++ ){
            if( sheets[page][rule].selectorText === selector ){
                css = sheets[page][rule].style;
                break;
            }
        }
        break;
    }
}

// Once you have located the desired CSS, you can access it accordingly.

console.log(css);
alert(css.backgroundColor);

// Here's an example extracted from actual code:

if(css.borderTopWidth)this.speaker_default.edge._sizediff=Number(css.borderTopWidth.slice(0,-2));

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

Initialization of Arrays with Default Values

I have taken on the task of converting a C++ program into JavaScript. In C++, when creating a dynamic array of type float/double, the entries are automatically initialized to 0.0; there is no need for explicit initialization. For example, a 1-D vector of ...

Filter an array using regular expressions in JavaScript

Currently, I am facing a challenge in creating a new array of strings by filtering another array for a specific pattern. For example: let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654" I believe this pattern can be ...

What is the process of creating a color range in Java?

I am looking for a way to input a 6-digit RGB-hex number and then be able to click on a button that will display the corresponding color name. Unfortunately, I have not been able to find a color library in Java that can provide me with the names of arbitra ...

vuejs function for modifying an existing note

Method for editing an existing note with Vue.js in a web application This particular application enables users to perform the following tasks: Create a new note View a list of all created notes Edit an existing note Delete an existing note Prog ...

Combining Json, Jquery Autocomplete, and PHP to customize the displayed search options based on multiple items within the Json data

I have a PHP file that returns an array of results, with the 'Name' field being one of them. I want to customize my jQuery autocomplete feature to only search by the 'Name' field and suggest results based on that. However, once a sugges ...

Designing a popup using Angular, CSS, and Javascript that is capable of escaping the limitations of its parent div

I'm currently working on an Angular project that involves components nested within other components. My goal is to create a popup component that maintains the same size and position, regardless of where it's triggered from. One suggestion I rece ...

What is the best way to retrieve router parameters within a JSX component?

How can I pass the post ID as a prop to the EditPost component in order to edit it? render() { return ( <Router> <Switch > <Route path="/edit/:id"> <EditPost index={/*what do I do here?*/} /> ...

Extracting object properties and tallying their occurrences

How can I extract a single property from an array of objects like the following: [{"name":"Bryan","id":016, "counter":0}, {"name":"John","id":04, "counter":2}, {"name":"Alicia","id":07, "counter":6}, {"name":"Jenny","id":015, "counter":9}, {"name":"Bryan" ...

Using Javascript to open a new page and execute a script

I need to be able to launch a new window window.open(url,'_blank'); After that, I want to execute a JavaScript script like this: window.open(url,'_blank').ready("javascript code here"); However, I'm unsure how to accomplish thi ...

Input must be either a 12-byte string, a 24-character hexadecimal string, or an integer

As a beginner in coding, I am struggling to understand and fix this issue. If anyone could lend a helping hand, I would be truly grateful. Error Message: BSONTypeError - Argument passed in must be a string of 12 bytes or a string of 24 hex characters or a ...

What is the best way to show an SVG icon in React without having to make an HTTP request for the file?

A special requirement for a react application is to display icons in certain parts of the application while offline. The use of inline svg is particularly fitting for this purpose. import React from 'react'; // Utilizing inline svg to showcase i ...

Tips for converting this ajax code to long polling

I am currently using this ajax code and I was wondering if anyone knows how to change it to long polling. Here is the code I am using: var chat = {} chat.fetchMessages = function () { $.ajax({ url: 'ajax/ajax/chat.php', type: 'PO ...

Set the position to fixed so it doesn't scroll

Is there a way to create a fixed position div that remains in place when the user scrolls, similar to the effect shown in this example image? Position Absolute: https://i.sstatic.net/4RAcc.png Position Fixed (desired effect): https://i.sstatic.net/3DIna. ...

Sorting multiple columns in Angular using the $filter and an array of predicate functions

For my Angular project, I need to order an array using the $filter('orderBy') function. Specifically, I want to specify three predicate callbacks and have the sort order be ASC, DESC, ASC. I am well aware that there are various methods to achiev ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

Is it possible to retrieve the ID instead of the country name in the autocomplete feature?

I implemented Autocomplete from @Mui in my component const Profile = () => { const { register, handleSubmit, setValue, formState: { errors }, } = useForm({}); const [countries, setCountries] = useState([]); const submit = asyn ...

How come my Calendar is not showing up on the browser?

I came across a helpful guide on setting up a Calendar in HTML using JavaScript You can find it here: Unfortunately, the code I tried to use based on that guide isn't functioning as expected. <div class="row"> <div class="col-lg-4 text ...

What is the process for retrieving the width value from an input field using jQuery?

This example demonstrates an alert trigger when the input value width or cursor crosses the input width. How can we retrieve the width of the input value without just getting the length of the value in jQuery? $('.value_width').text($('.i ...

Consolidate duplicate list entries and adjust the CSS as needed

Imagine I have an array like this: myarray = ["apple", "apple", "apple", "potato", "apple"]; myarray = ["apple", "apple", "apple", "potato", "apple"]; function listCreate(data) { var output = '<ul>'; $.each ...

What are the steps for importing KnockOut 4 in TypeScript?

It appears straightforward since the same code functions well in a simple JS file and provides autocompletion for the ko variable's members. Here is the TypeScript code snippet: // both of the following import lines result in: `ko` undefined // impo ...