Exploring the world of CSS: accessing style attributes using JavaScript

So I created a basic HTML file with a div and linked it to a CSS file for styling:

HTML :

<html>
<head>
    <title>Simple Movement</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <script src="index.js"></script>
</head>

<body>
    <div id="square"></div>
</body>
</html>

CSS:

body {
    margin: 0;
}

#square {
    width: 100px;
    height: 100px;
    border: 1px solid #095057;
    background-color: #20979e;
    position: absolute;
    left: 200px;
    top: 200px;
}

In my JavaScript file, I have a log statement like this:

console.log(document.getElementById('square').style.top)

But unfortunately, I am encountering an error message:

   Uncaught TypeError: Cannot read properties of null (reading 'style')
at index.js:1

I am puzzled as to why it is saying that the style property is null. Any ideas?

Answer №1

I'm not sure why it's showing that the style is null. Do you have any ideas?

Actually, it's not about the style being null. The issue lies in the fact that

document.getElementById('square')
is returning null, so when you try to access the property style on null, it results in an error.

This problem occurs because your script is being loaded and executed in the head section. At this point, the element with the ID "square" doesn't exist in the DOM yet.

To resolve this, you can either move your script below the relevant element (check the snippet) or use async defer like this:

<script src="index.js" async defer></script>
to ensure that it loads and executes after the DOM parsing is complete.

Additionally, keep in mind that accessing the style will only give you inline styles from the style attribute and won't include values from external stylesheet files or inline stylesheets. If you need all the computed styles, consider using computedStyleMap() (refer to https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap).

body {
  margin: 0;
}

#square {
  width: 100px;
  height: 100px;
  border: 1px solid #095057;
  background-color: #20979e;
  position: absolute;
  left: 200px;
  top: 200px;
}
<html>

<head>
  <title>Simple Movement</title>
  <meta charset="UTF-8">
</head>

<body>
  <div id="square"></div>
  
  <script>
    console.log(document.getElementById('square').computedStyleMap().get('top').value);
  </script>
</body>



</html>

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

Error encountered while executing ExpressJs function that was converted to a promise

Understanding how errors are handled in promises can be a bit tricky, especially for someone new to promises like myself. I'm trying to make the most of them, but I'm not quite there yet. Here is the code snippet I'm working with: app.list ...

What is the best way to pass information between Express middleware and endpoints?

Many middleware packages come with factories that accept an options object, which often includes a function to provide necessary information to the middleware. One example of this is express-preconditions: app.use(preconditions({ stateAsync: async (re ...

Ensuring the Selection with jQuery

I've successfully implemented jQuery validation on a text field, but when I try to apply it to a radio button, it doesn't seem to work. I'm not sure what I'm doing wrong. Here is my HTML and jQuery code: <input type="text" placehol ...

Real-time JQuery search with instant results

While utilizing a custom script to display search results on the page, I encountered an issue when typing long sentences. Each request goes to the server, resulting in delayed responses that stack up and cause the div to change quickly. This is not the des ...

Using jQuery to dynamically insert an HTML element into a table

I'm trying to insert a hyperlink into an empty HTML table. This function works perfectly fine on Firefox and Chrome, taking only 0.2 seconds to load. However, when I try it on IE9, it takes at least 3 minutes to display the link. The issue seems to be ...

Tips for integrating highcharts plugins with highcharts-vue (highcharts vue wrapper)

Currently, I am utilizing the Vue wrapper for Highcharts called highcharts-vue(https://github.com/highcharts/highcharts-vue). However, I am facing an issue where I need to detect the event of a right mouse click (contextmenu) on the chart. To address this, ...

If the given response `resp` can be parsed as JSON, then the function `$

I was using this script to check if the server's response data is in JSON format: try { json = $.parseJSON(resp); } catch (error) { json = null; } if (json) { // } else { // } However, I noticed that it returns true when 'res ...

Various options can be chosen to alter the margin

$('#cpseltop').change(function() { var a = $(this).val(); $('.cpselhide').hide(); $('#cpsel' + a).show(); }); .cpselect{ display:block; border:1px solid #999; border-radius:9px; outline:none; width:100%; padding:2px 5px; curso ...

Trouble with HR functionality in Outlook email

<table> <tr> <td class="h1" colspan="12" style="font-family: 'proxima_nova_rgbold', Arial, Helvetica, sans-serif;font-size: 18px;text-align:center; padding-top:10px;padding-left:30px;text-transform: uppercase;padding-bottom: 8 ...

Can anyone recommend an easy regular expression to validate date format patterns?

While searching for regex patterns to validate date values in a specific format, I came across numerous options. However, I prefer to allow users to input their own custom date patterns such as: d-mm-yyyy MM/dd/yy yyyy.mm.d I am looking for a ...

Connect radio input's value to object's key within AngularJS

Within my controller, I currently have an object structured as follows: $scope.colors = { green: "Green", yellow: "Yellow", red: "Red" }; I am attempting to dynamically generate radio inputs and then link the input value to the corresponding ...

Text positioned on the right side of the image, appearing to hover above

After finding a helpful example on Stack Overflow, I successfully implemented a similar layout for product boxes in a JSFiddle. I then replicated the CSS and HTML almost exactly on my Wordpress blog, but encountered an issue where the title, description, a ...

The CSS styles can vary depending on the web browser being used

Require assistance with my CSS. I designed an HTML/CSS widget on Blogger using my own expertise, but now facing some issues. The trouble arises with the image on the front left in the code. While it displays correctly on Google Chrome, aligned with the te ...

Waiting for the listener script to finish its task in an Ajax call and then informing the user

I have developed a unique program that allows users to submit test cases from a specific webpage (main.php). The webpage triggers an ajax request to insert user data into MySQL using the file insert.php, with the value done=0. Subsequently, there is a list ...

Tips for altering promises within nested for loops?

Presented below is a complex function that aims to extract model variants from a csv file, which are stored as strings in an array. The path of this csv file depends on information obtained from other csv files, hence the need for looping. The csvService. ...

Preserving spacing using minimum widths

Looking for some help with a page layout issue. I have a header on my page with a title and menu. Currently, the header has a margin and a minimum width set to the width of the menu. However, when the user resizes the window and reaches the minimum width, ...

Changing the color of a div while implementing a show and hide effect in JavaScript

I have designed a checkout system with three distinct parts - shipping information, billing information, and order confirmation. These sections are all on the same page, allowing for a seamless flow during the checkout process. Once a customer completes t ...

Ways to expand the capabilities of Google Analytics for tracking AJAX requests and more, as recommended by the H5BP documentation

I need assistance with installing the Google Analytics enhancements mentioned in the extend.md file of H5BP (https://github.com/h5bp/html5-boilerplate/blob/v4.3.0/doc/extend.md). The documentation mentions using a specific code snippet for optimized Googl ...

Avoiding errors caused by higher order array methods

Is there a way to avoid errors when filtering data? The function below may encounter issues at conversationMember.Name.toLowerCase() if conversationMember is not present. This function is part of a computed property in a Vue application. Feel free to ask ...

Hovering over a td tag and adding a border using CSS can cause the entire table to

While experimenting on a coding platform: <table> <tr> <td class="changeme">something</td> <td>something</td> <td>something</td> <td>something</td> < ...