The code encountered an error because it was unable to access the property 'style' of an undefined element on line 13 of the script

Why is it not recognizing styles and showing an error? All paths seem correct, styles and scripts are connected, but it's either not reading them at all (styles) or displaying an error. Here is the html, javascript, css code. How can this error be fixed? Is something wrong in general?

html:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src = "script.js">
    </script>
    <TITLE></TITLE>
  </head>
  <body>
<div class="cookie_notice">
    This site uses cookies
    <div>
        <a class="cookie_btn" id="cookie_close" href="#close">Agree</a>
        <a class="cookie_btn" href="#politika">privacy policy</a>
    </div>
</div>
  </body>
</html>

JS:

function getCookie(name) {
    let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ));
    return matches ? decodeURIComponent(matches[1]) : undefined;
}
let cookiecook = getCookie("cookiecook"),
cookiewin = document.getElementsByClassName('cookie_notice')[0];    
if (cookiecook != "no") {  
    cookiewin.style.display="block"; 
    document.getElementById("cookie_close").addEventListener("click", function(){
        cookiewin.style.display="none";    

        let date = new Date;
        date.setDate(date.getDate() + 1);    
        document.cookie = "cookiecook=no; path=/; expires=" + date.toUTCString();               
    });
}

css:

.cookie_notice {
    display: none;
    position: fixed;
    z-index: 9999999;
    bottom: 0;
    left: 0;
    right: 0;
    text-align: center;
    font-size: 15px;
    font-family: Verdana, sans-serif;  
    color: #FFF;
    background: #337AB7;
    padding: 10px 20px; 
    border-top: 4px solid #BFE2FF;
}
.cookie_btn {
    display: inline-block;
    margin: 10px 6px 4px 6px;
    text-decoration: none;
    position: relative;
    font-size: 13px;
    padding: 4px 12px;
    color: #FFF;
    font-weight: bold;
    text-transform: uppercase; 
    background: #337AB7;
    border: 2px solid #BFE2FF;
}
.cookie_btn:hover {
    color: #FFF;
}
.cookie_btn:after,
.cookie_btn:before {
    position: absolute;
    height: 2px;
    left: 50%;
    background: #FFF;
    bottom: -6px;
    content: "";
    transition: all 280ms ease-in-out;
    width: 0;
}
.cookie_btn:before {
    top: -6px;
}
.cookie_btn:hover:after,
.cookie_btn:hover:before {
    width: 100%;
    left: 0;
}

Answer №1

Have you considered placing the <script> tag at the bottom of the page? Just like this:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title></title>
  </head>
  <body>
<div class="cookie_notice">
    This site uses cookies
    <div>
        <a class="cookie_btn" id="cookie_close" href="#close">Agree</a>
        <a class="cookie_btn" href="#politika">privacy policy</a>
    </div>
</div>

<script src = "script.js">
    </script>
  </body>
</html>

There you have it!

Answer №2

When reading HTML, it's important to remember that the script is executed before the rest of the page is displayed.

const cookieElement = document.getElementsByClassName('cookie_notice')[0];

Attempting to access an element that hasn't loaded yet will result in a value of undefined. To solve this issue, place the script right before the closing body tag.

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

AJAX request is successful, however, the database remains empty with no data being inserted

I have been attempting to utilize ajax and php to insert data into a database, but for some reason, it is not functioning as expected. Despite validating all the itemName, category, and price fields in the html file, the data being inserted into the data ...

Changing the name of a React Native sample application

I am currently working on a project based on this App example: https://github.com/aksonov/react-native-router-flux/tree/master/Example When I tried to change the following lines: index.ios.js import App from './App'; AppRegistry.regist ...

Support for Chrome in Angular 8

Can someone please advise on the minimum version of Google Chrome that is supported by Angular 8? Additionally, I am looking for a way to prompt users to update their Chrome browser if it doesn't meet the required version. My Angular application seems ...

Encountering an error message of "Cannot POST" while trying to send data through a REST client application

Upon my attempt to add a new entry into the Doctors database I created, I encountered an error that has left me perplexed. This is how my server.js file appears: const express = require('express'); const bodyParser = require('body-parser&a ...

Choose all checkboxes across the entire webpage

Given the code below: <input type="checkbox" name="categories[9507]"> Is there a way to write a JavaScript command that can automatically select all checkboxes with similar naming structures on the entire page? The only difference in the names is t ...

Install the npm package if there have been modifications to the package.json file

In short: Can we make npm install run automatically before executing any npm script if the package.json file has been modified? Situation Summary Imagine you switch to a branch that has updated the package.json file. You try running npm run my-script, bu ...

Customize the yellow background color of Safari's autofill feature by following these simple

When I open this image in Safari, this is what I see: https://i.stack.imgur.com/KbyGP.png However, this is the code I have: https://i.stack.imgur.com/4wEf0.png References: How to Remove WebKit's Banana-Yellow Autofill Background Remove forced ye ...

Experiencing problems with integrating Slim framework and AngularJS, such as encountering a 404 error

Although this may seem like a repeat question, I am encountering an issue with using AngularJS with Slim Framework web services. I have set up a webservice to retrieve a student record with a URL structure like: http://www.slim.local/api/getstudent/1 ...

"Maximizing the power of Jquery's .each function. What

In my jQuery code, I have the following: function lshow() { var delayt = 500; var showtime = 5000; var ArrayOfElements = ['.slogan1','.whatwedo','.ekon','.ene', '.ekol', '.sm&a ...

Steps for deactivating tab stops on the primary webpage in the presence of a snackbar

On my web page, there are multiple drop-down menus, input fields, and buttons that can be interacted with using both the tab key and mouse. After entering certain data, I trigger a snackbar (source: https://www.w3schools.com/howto/howto_js_snackbar.asp) t ...

Integrate, Delay, Experimentalize, and Attach components

This inquiry might lean more towards a general browser/javascript discussion rather than a focused prototype question, but I believe this community possesses a deep understanding of javascript and browsers. With that said, here is my query: If the followi ...

Acquiring administrative authorization upon user login with PHP

I have developed a registration form and a login form using PHP. However, whenever I run this code, it displays the message "invalid username" when the username is invalid, or it says "your account isn't approved by admin yet." Can anyone please guide ...

Dynamically load the configuration for a JQuery plugin

Currently, I am utilizing a JQuery plugin from this source. My goal is to dynamically load the configuration of the plugin without directly modifying it within the plugin file. Below are the default options provided by the plugin: $.Slitslider.def ...

Javascript Macros for Mastering Excel

My goal is to use Javascript macros to handle excel spreadsheets instead of the standard VBA. I have found a way to run javascript code through VBA, as shown below: 'javascript to execute Dim b As String b = "function meaningOfLife(a,b) {return 42;}" ...

Link your 3D force graph node by attaching it

How can a link be attached to the nodes in 3d-force-graph (https://github.com/vasturiano/3d-force-graph) so that clicking on a node redirects the user to a specific or customized URL? ...

Express Power Tool - Error: app.set function is undefined

My journey with creating an API using Node/Express began with a solo endeavor to learn the basics in a 'naive' manner. The initial setup worked smoothly, prompting me to experiment with express-generator. Upon completion of the setup process, th ...

The flipping action will only occur on the initial card

I am working on creating a unique photo gallery that allows users to flip the picture by clicking or tapping on it. Once flipped, users will be presented with additional information about the image and a link. I have included all of my CSS, JS, and HTML be ...

When the Ionic app is relaunched from the side menu, the view fails to refresh

When I open my Side Menu, I initially see two options - scan barcode or search product. Once I choose one, the rest of the view is filled in dynamically. The issue arises when I try to go back to the Side Menu and reload the view to only display the origin ...

Sharing data between React JS components Passing information between different components in React JS

My NavBar.js component contains login information for the logged-in user. It displays "Welcome" along with the user details when the user is logged in. Now, I want to replicate this functionality in the ProductList.js component so that when a user posts a ...

What is the best way to smoothly transition in an image that is dynamically set using Angular?

I am using Angular to set a background image for my page, but the current loading behavior is not visually appealing as the image loads from top to bottom. I would like to implement a fade-in effect or load the image from a blurry view to enhance the user ...