Leverage JavaScript to retrieve the formatting of an element from an external CSS stylesheet

Check out this HTML snippet:

<html>
    <head>
        <link rel="stylesheet" type="text/css" media="all" href="style.css">
    </head>

    <body>
        <div id="test">Testing</div>

        <script>
            alert(document.getElementById('test').style.display);
        </script>
    </body>
</html>

This is the content of style.css:

div {
    display:none;
}

The issue I'm facing is that instead of getting "none", the JavaScript code returns an empty string. Any suggestions on how to fix this problem would be greatly appreciated!

Answer №1

This solution is compatible with modern browsers that adhere to web standards (excluding IE - due to its use of currentStyle/runtimeStyle).

<body>
    <div id="test">Testing</div>

    <script type="text/javascript">
        window.onload = function() {
            alert(window.getComputedStyle(document.getElementById('test'),null).getPropertyValue('display'));
        }
    </script>
</body>

Answer №2

If you want to retrieve the display style property indirectly, you'll need to obtain the computed value instead of setting it directly in the code provided above.

For instructions on how to achieve this, please visit the following page: Get styles

To effectively retrieve the value, follow these steps:

var displayValue = getStyle("test", "display");

function getStyle(el,styleProp)
{
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

Answer №3

The CSS file may not have loaded yet. Make sure to enclose your JavaScript code within an "on-ready" event.

<body onload="alert(document.getElementById('test').style.display);">

Did this solution resolve the issue for you?

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

Is there no "on" function available in the Node readline module?

I am currently working on building a Node.js application that reads a text file line by line using the 'readline' module and displays it in the console. var lineReader = require('readline'); lineReader.createInterface({ input: fs.cre ...

Caution: Make sure to assign an object to a variable before exporting it as the default module

While working with react-redux, my root Reducer appears like this: import Customers from "./customers/reducer"; export default { Customers }; Recently, I encountered a warning saying: Assign object to a variable before exporting as module def ...

accessing the php script within a node environment

Hey there! I'm currently working on creating a chat system using socket.io, express.io, and node.js. So far, everything has been going smoothly as I've been following the documentation provided by these tools. However, when I attempt to integrat ...

Retrieving data from a file results in receiving blank strings

Struggling to access the data within a directory of files, I've encountered an issue where the data doesn't seem to be read correctly or at all. Even though there is content when opening the files individually, when attempting to examine their co ...

Substitute empty spaces and organize the text layout

I'm struggling to figure out how to substitute the whiteSpace in an aggregate request using MongoDB and also how to remove a specific part of a string (most likely requiring regex). Here's an example of my document: { "_id": "57dfa5c9xxd76b ...

Sharing context sub files in Next.js can be easily accomplished by following a few simple

These are the pages on my website: /pages /gift /[slug] index.tsx /personalize index.tsx In /gift/[slug]/index.tsx, I have a component called GiftProvider that looks like this: return ( <GiftProvider gift={gift}& ...

What steps can be taken to ensure that the design of this page flows seamlessly?

Interested in a design similar to this <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Title</title> <style> html, body { height: 100%; margin: 0; } .wrapper { min-height: 250p ...

Having trouble compiling for IOS using a bare Expo app? You may encounter an error message that reads "Build input file cannot be found."

Encountering Error When Running react-native run-ios on Bare Expo App I am experiencing an issue while trying to run the 'react-native run-ios' command on my Bare expo app. The error message I am receiving is: "Build input file cannot be found: ...

Is it feasible to execute exe files within a ReactJS environment?

Hey there! I've created a Game Launcher using ReactJS for my Unity game and was wondering if it's feasible to start the game (an exe file) simply by clicking on the play button. Can anyone please advise me on this? ...

Use jQuery to create a price filter that dynamically sets slide values based on the filter object

I'm currently utilizing the jQuery slide filter to sort products based on price. The filtering value is set within the script, but I am interested in dynamically setting it based on the highest/lowest number found on my page using a data attribute. D ...

How to bind parent object scope to MySQL query's anonymous callback in Node.js

As a newcomer to node.js, I am still working on understanding the concept of scoping anonymous functions. I have created an object with multiple methods and within one of my methods, I retrieve a MySQL connection from a pool and then execute a query on tha ...

Having trouble retrieving information from .pipe(map()) method

Encountering some issues with Observable handling. I have a function that returns an Observable. public getData(userId) { const data = this.execute({userId: userId}); return {event: "data.get", data: data} } private execute(input: SomeDt ...

Exploring the power of AngularJS in manipulating Google Maps polygons with the help of ng-repeat

I recently started using a Google Maps plugin specifically designed for AngularJS, which can be found at . My goal is to display polygons on the map, so my HTML code looks something like this: <google-map center="map.center" zoom="map.zoom" draggab ...

Utilizing Visual Studio: Implementing jsmin in post-build actions

After attempting to add jsmin.exe as a post-build event in my VS 2010 project, I encountered an "error code 9009" when building the project. I tested this in the command prompt and found that it works if I navigate to the folder and run: jsmin < debug ...

Change the state of items in a React component to either disabled or active depending on the active items list retrieved from the API

Obtained from the API, I have a collection of buttons that are displayed for filtering: For instance: button2 button4 button5 Assuming there are a total of 5 buttons. button1 and button3 are supposed to be in a disabled or inactive state (appearing ...

Utilizing JavaScript for selecting a radio button on click event

I have implemented a feature with four radio buttons to select a country. Upon clicking on any of the radio buttons, I utilize Ajax to retrieve the states corresponding to that specific country. To indicate to the end user that data processing is ongoing, ...

Implementing setInterval() leads to the dynamic alteration of images

I've created Marquees using CSS animations and a countdown timer. The Marquees display 100 random images that move from left to right and right to left. However, when the countdown timer decreases, the images in the Marquee change but the scrolling co ...

Tips for accessing array or JSON data with ReactJS

As a novice with the MERN stack, I have set up my express app to run on port 3001 with a dbconn route. When I access "localhost:3001/dbconn," it displays the docs array successfully. const mongoose = require('mongoose') const MongoClient = req ...

Chrome fails to read font family correctly

I created a jsfiddle that demonstrates an interesting behavior with setting and reading the font-family using jQuery. When I set the font-family to "Arial . . ." it reads back okay, enclosed in a single set of double quotes. However, when I set the font-fa ...

Efficiently updating database records without the need for page reloads using EJS

I'm working on a project that resembles the comment section on Reddit. Users can leave comments and others can reply to those comments. My tech stack includes Node, Express, MySQL, and EJS. The issue I'm facing is implementing the upvote/downvo ...