The values in my JavaScript don't correspond to the values in my CSS

Is it possible to retrieve the display value (display:none; or display:block;) of a div with the ID "navmenu" using JavaScript? I have encountered an issue where I can successfully read the style values when they are set within the same HTML file, but not when they are defined in an external CSS file.

Here is the code snippet:

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="styles.css" rel="stylesheet" type="text/css" media="screen" />
</head>

<body>
    <div id="navmenu">
<p>This is a box of 250px * 250px</p> 
</div><!--navmenu-->
<!------------------------------------------------------------------->
<script>
function display(elem) {
  return elem.style.display;
}
alert(display(document.getElementById('navmenu')));
</script>
<!------------------------------------------------------------------->
</body>
</html>

And here is the CSS:

#navmenu {
    display:block;
    width:250px;
    height:250px;
    background-color:#3CC;
}

Answer №1

When using the elem.style.display property, keep in mind that it only reflects a display property directly set on the DOM object and does not consider inherited styles from style sheets.

To obtain a style value that includes those from a style sheet, you can utilize the window.getComputedStyle() method.

function showDisplayValue(elem) {
    return getComputedStyle(elem, null).getPropertyValue("display");
}

Answer №2

To utilize the getComputedStyle() method, follow this code snippet:

function checkDisplay(element) {
  return window.getComputedStyle(element).display;
}
alert(checkDisplay(document.getElementById("sidebar")));
<div id="sidebar">
  <p>This is a sidebar with a width of 300px.</p>
</div>
<!--sidebar-->

Answer №3

Here is a handy function you can use to easily query the display style of any element using the getComputedStyle method. This function simplifies the process and also caches the computed style object for efficiency.

function getStyle(query) {
  var elem = document.querySelector(query),
      cs = window.getComputedStyle(elem,null);
  return {
     get : function(prop) {
        return cs.getPropertyValue(prop);
     }
  }
}

To use this function, simply provide a CSS selector for the element you want to query. For instance, if you have an element with ID "navmenu", you can query it like this:

var s = getStyle( "#navmenu" );

s.get("display");
s.get("color"); // etc...

This function works in IE9 and above.

Answer №4

When you access the HTMLElement.style property, you are actually getting a CSSStyleDeclaration object that specifically represents the style attribute of the element. For a comprehensive list of CSS properties that can be accessed through style, refer to the CSS Properties Reference.

It's important to note that using the style property alone may not provide a full picture of an element's style, as it only reflects the CSS declarations set within the element's inline style attribute. It does not capture styles applied from external sources like style rules in the head section or external style sheets. To retrieve all CSS property values for an element, it is recommended to utilize window.getComputedStyle() instead.

Source

The solution lies in using window.getComputedStyle() instead.

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

Transferring multiple data between PHP and JavaScript

Here is the code I am using for the on change event: <script> $('.BIR').change(function() { var id = $(this).val(); //get the current value's option $.ajax({ type:'POST', dataType: "json", ...

Customizing SVGs for Ion Icons Version 5 in a React Application

I have been using ion icons in React by importing them directly into my index.html. While this method has been working well with the icons from ion icons found here, I know that you can also use custom SVGs by specifying an src attribute in the ion-icon ta ...

showing information on webpage 2 received via query parameters from webpage 1

Hello, I am trying to input text into a textarea and then send the data through a query string to another webpage. My goal is to display the data on the second webpage. I have written the following code, but it doesn't seem to be working. I've ch ...

Activate Gulp watcher to execute functions for individual files

I have developed a specific function that I need to execute only on the file that has been changed with gulp 4.0 watcher. For example, the current task setup looks like this: gulp.watch([ paths.sourceFolder + "/**/*.js", paths.sourceFolder + "/**/ ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

Performing asynchronous operations in React with axios using loops

On the backend, I have a socket set up to handle continuous requests from the server. Now, my goal is to send requests to the backend API continuously until a stop button is clicked. Using a loop for this task is considered bad practice as it never checks ...

Setting up React Native on a Mac M1 device

I am currently setting up React Native on my MacBook M1 Despite having installed npm, JDK, Node, Rosetta, CocoaPod, VSCode, Android Studio, Xcode and more, when I try to run the command (npm start), the directories for iOS and Android are not present. The ...

Unusual marking on the navigation bar

Currently, I am making updates to a website that was created by a previous employee long before I joined the team. One of the requested changes is to eliminate the orange box surrounding the navigation links. The navigation appears to be generated using Ja ...

The issue with the Angular custom checkbox directive arises when using it within an ng-repeat

A personalized directive has been developed for checkboxes that is applicable throughout the application. The code for creating the checkbox is as follows: JS angular.module("myApp") .component("ngCheckbox", { template: '<di ...

Is there a way to dynamically enable ui-sref through element.append in Angular?

I am in the process of developing a pagination directive. Once the total_for_pagination data is filled, the appropriate HTML for the pagination gets generated. Here's my current HTML structure with a maximum of 50 per page: <pagination data-numbe ...

Unlocking the Power of Observable Objects with Knockout.js

Recently delving into knockoutjs, I came across the Microsoft tutorial showcasing how to integrate knockoutjs with MVC Web API. The tutorial can be found at: https://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-8. In a particu ...

Utilizing both a named function and an arrow function as event handlers in React

Can you spot the issue in the code snippet below? export default function App() { const [count, setCount] = useState(0); return ( <div className="App"> <h2>{count}</h2> <button onClick={() => { ...

Seeking a template for a server-side programmer who lacks proficiency in CSS and design?

Hey there all you wise folks! So here's the deal - I'm a PHP/JavaScript wizard when it comes to logic and server-side stuff, but I really suck at design, CSS, and all things arty. Does anyone have any recommendations for a template or tool that ...

React Redux Loading progress bar for seamless navigation within React Router

Currently, I am working on adding a loading bar similar to the one used by Github. My goal is to have it start loading when a user clicks on another page and finish once the page has fully loaded. In order to achieve this, I am utilizing material-ui and t ...

Does an href and click events both happen simultaneously?

JavaScript Purpose: Implement a series of loops and create anchor links with the 'href' attribute <a class="mui-control-item" v-for="(item, index) in dai" v-on:click ="abc(item)" :href="'#item'+(index+1)+ 'mobile'" ...

Retrieving complete credit card information with the help of JavaScript

I've been grappling with extracting credit card data from a Desko Keyboard, and while I managed to do so, the challenge lies in the fact that each time I swipe, the card data comes in a different pattern. Here is my JavaScript code: var fs = require ...

Trigger JavaScript function once all Ajax requests have completed

Seeking assistance with troubleshooting JavaScript code that is not functioning as expected. The Application sends file names to the server via Ajax calls for processing, but I need to update the database once all imports are complete. The problem arises ...

Node.js offers a simple and efficient way to retrieve screen resolution. By using

I am trying to retrieve the screen resolution using node.js, but the code snippets provided are not working as expected. var w = screen.width; var h = screen.height; The following code also did not work for me: var w = window.screen.width; var h = windo ...

Can someone guide me on the process of adding a personalized emoji to my discord bot?

After creating my own discord bot, I'm ready to take the next step and add custom emojis. While tutorials have helped me understand how to use client.cache to type an emoji, I'm unsure of how to upload them and obtain their ID for use in my bot. ...

Express middleware for handling errors with Node.js router

My application structure is laid out as follows: - app.js - routes ---- index.js The ExpressJS app sets up error handlers for both development and production environments. Here's a snippet from the app.js file: app.use('/', routes); // ro ...