The error message "Uncaught TypeError: Unable to access 'style' property of undefined" was encountered

I'm attempting to dynamically adjust the width of certain HTML elements using JavaScript, specifically by utilizing the innerWidth property.

Here is the code snippet I've written:

$(document).ready(function () {
    var footer = document.getElementsByTagName('footer')[0];
    var header = document.getElementsByTagName('header')[0];
    footer.style.width = window.innerWidth - 400;
    header.style.width = window.innerWidth - 400;
});

The purpose of using JavaScript to set the widths of the header and footer is to prevent potential overflow issues that could lead to a scrollbar being added.

Below is my accompanying HTML markup:

<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <header>
        <div id="img_container">
            <a href="#"><img id="header" src="img/Header.png"></a>
        </div>
        <nav>
            <ul>
                <li><a href="#">text</a>
                    <ul>
                        <li><a href="#">text</a></li>
                        <li><a href="#">text</a></li>
                        <li><a href="#">text</a></li>
                        <li><a href="#">Text</a></li>
                    </ul>
                </li>
                <li><a href="#">Text</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>
        <a href="#"><img id="img" src="img/img.png"></a>
    </header>
    <footer>
        <div id="footer_container">
            <div id="footer_el">
                <span class="header">Services</span>
                <hr> Bunch of links and text
            </div>
            <div id="footer_el">
                <span class="header">Text</span>
                <hr> Bunch of links and text
            </div>
            <div id="footer_el">
                <span class="header">About us</span>
                <hr>
                <a href="#">Some text</a>
                <br>Contact us:
                <br>Email
                <br>Phone number
            </div>
            <div id="footer_el">
                <span class="header">Partners</span>
                <hr> Yaadiyaadiyaa
            </div>
        </div>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <div>Some text...
        </div>
    </footer>
</body>

</html>

Displayed below is the error message currently appearing in my Google Chrome browser console:

Answer №1

If your page includes a header and footer, make sure your code returns them correctly. If they are not present on the page, you may encounter the error mentioned above. It is important to remember to add "px" at the end of the statements for the width settings to take effect.

$(document).ready(function() {
  var footer = document.getElementsByTagName('footer')[0];
  var header = document.getElementsByTagName('header')[0];
  footer.style.width = (window.innerWidth - 400) + "px";
  header.style.width = (window.innerWidth - 400) + "px";
});
header {
  background-color: red;
}
footer {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  <h1>Header</h1>
</header>
<footer>
  <h1>Footer</h1>
</footer>

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

Bringing Together AngularJS and JQuery: Using $(document).ready(function()) in Harmony with Angular Controller

Can you lend me a hand in understanding this? I have an angular controller that is structured like so: angular.module('myApp', []) .controller('ListCtrl', function($scope, $timeout, $http){ // Making API calls for Health List ...

Choosing an ID along with a numerical value in jQuery

Being new to both stackoverflow and jQuery, I'm facing a challenge in creating a basic function. In my website, there are multiple links with IDs such as "filtro1", "filtro2", and so on. My goal is to write a single piece of code that will be trigger ...

Rearrange content blocks by clicking on the image

In my image gallery, each image is accompanied by a div containing its name. However, I'm facing an issue where clicking on the image causes the name div to disappear (as intended), but I am unable to replace it with the tools div (with class "ImageBu ...

Is data-method not supported by Express?

After gaining expertise in Rails and HTML, I discovered how Rails can handle the "Delete" method using code like: <a rel="nofollow" data-method="delete" href="/logout">Log out</a> However, when transitioning to node and express, the web serve ...

What is the best way to choose a child element that has been clicked using jQuery?

How can I make only the child of the clicked element slideToggle? I tried implementing a solution, but it ended up sliding all divs with the .description class. Can anyone provide some guidance? HTML: <div id="container"> <div class="row"> ...

Managing login API tokens in Vue JS

I have implemented a custom Login component in my Vue project: var Login = Vue.extend({ template: '#auth', data: function () { return {username: '',password: '',errorMessage:''}; }, methods : ...

Tips on expanding the row number column width in jqGrid

Within my JQuery Grid, I am utilizing a parameter called rownumbers. jQuery("#dateInfo").jqGrid({ url : theURL, datatype : "json", sortable: false, colNames:['Date & Time'], colModel:[{name:'arrivalTime',index:'arrivalTime& ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

Having difficulty transferring JSON data from Ajax to a PHP variable

After successfully capturing the JSON / Ajax response in the id of a span, I am facing an issue with saving the response in a PHP variable. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script ...

Trouble encountered while transforming JSON information into an HTML table with Vue.js scripting

Presented below is an HTML file containing Vue Js code: <!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min. ...

Manage responses from ajax submission

My settings form has a unique feature to prevent users from making changes by mistake. After completing the form, users click the save button to trigger a modal (using Bootstrap modals) asking for their password before processing the original form. If the ...

Error 404 encountered while attempting to download a file through the <iframe> and AJAX method

I am currently utilizing an iframe to initiate the downloading process of an excel file from the server via an AJAX request. Each time a button is clicked, the server generates an excel file within approximately thirty seconds and sends back the correspond ...

The primary division containing two inner divisions, one centered and the other positioned to the right

I would like the layout to resemble the image provided. The div header contains two nested divs - the logo div should be centered, and the info div should be positioned to the right with some margin. ...

The resizing of images is limited to when the browser is refreshed for responsive

Hey there, I'm currently facing an issue with a responsive image gallery using jQuery cycle. If you want to check out my fiddle, here's the link - https://jsfiddle.net/qxyodctm/5/ <html>See jsfiddle</html> The problem occurs when t ...

space required on the upper side of the cell

I have formatted a text (including title and paragraph) in a cell using CSS styles to achieve the desired appearance. The only thing left is to create some space between the top of the Title and the content below it. I attempted to use the margin parameter ...

Issues with connecting static files in express.js

Hey there! I'm having an issue with the redirect not working when I click the "Submit" button on the login page. The code in my index.js file looks like this: app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dir ...

Verify user identities using just their passwords

For my express app, I'm tasked with creating an authentication system that uses a 4-digit pin as the password. The code is set up to save and hash the pin along with other user information when adding a new user. Since this is for an in-house server h ...

The Slider.prepend() function in lightSlider is not functioning as intended for the 'onSliderLoad' event in lightGallery

I implemented lightslider with lightGallery in the onSliderLoad function. There are two sets of code snippets included in my HTML code. You can find the complete code on this jsfiddle link. Code 1: Displays lightGallery view on page load, rendering images ...

The sticky navigation bar is not returning when scrolling up, and the function to remove the class is not working properly

After implementing a navigation bar that works on scroll down, I ran into an issue where it doesn't stop at the original position on scroll up. Despite finding a similar post addressing this problem, I struggled to apply the solution correctly due to ...

How to use addclass in AngularJS?

Can someone assist me with converting this to jQuery? $('.toggle').on('click', function() { $('.container').addClass('active'); }); $('.close').on('click', function() { $('.container&ap ...