Error: Unable to access the property 'fontSize' as it is undefined

<!DOCTYPE HTML>
<html>
    <head>
        <title>Interactive Web Page</title>
        <link id="mycss" rel="stylesheet" href="mycss.css">
        <script>

            function resizeText(size) {
                var styleSheet = document.getElementById('mycss').href;
                if (styleSheet.style.fontSize == '2.0em') { 
                    styleSheet.style.fontSize = parseFloat(styleSheet.style.fontSize) + (size * 0.2) + "em";
                } else if (styleSheet.style.fontSize == '3.0em'){
                    styleSheet.style.fontSize = parseFloat(styleSheet.style.fontSize) + (size * 0.3) + "em";
                }
            }

        </script>
    </head>
    <body id="theBody" class="theBod">
        <h1 id="h1" onclick="clickChange();">Hello</h1>
        <p id="para1" class="para1" onclick="resizeText(1);">Here is some text with a different size (click)<p>
        <p id="para2" class="para2" onclick="resizeText(2)">More text with another size on click.<p>
        <p id="demo" onclick="countToNum()"> Numbers (Click): </p>
    </body>
</html>

I am creating a web page where the text size increases when an element is clicked based on the specified parameter in the onclick function. This functionality modifies content using an external stylesheet.

#para1 {
    font-size: 2.0em;
}

#para2{
    font-size: 3.0em;
}

The error message "Cannot read property 'fontSize' of undefined," keeps appearing, but I want the JavaScript to only enlarge the clicked element while keeping others unaffected. Any assistance would be highly appreciated as I struggle with JavaScript coding.

Answer №1

The main idea:

All I want is to have the javascript respond and enlarge only the clicked element

In order to achieve this, there is no need to access the stylesheet; instead, simply access the style information of the element that was clicked:

<p onclick="resize(this)">...</p>

Next,

function resize(element) {
    var elementStyle = element.currentStyle || getComputedStyle(element);
    // Access and possibly modify elementStyle.fontSize here
}

Regarding the code in your query: This line:

var styleSheet = document.getElementById('mycss').href;

Returns a string with the URL of the stylesheet. It does not retrieve the actual stylesheet. Since strings do not have a style property, styleSheet.style will be undefined, and attempting to read styleSheet.style.fontSize will fail as you are trying to access a property from undefined.

If you wish to access the stylesheet information, you should search for the stylesheet within the document.styleSheets collection.

Alternatively, based on the HTML5 specification, HTMLLinkElement implements the LinkStyle interface defined by CSSOM, which implies that on compliant browsers, you could utilize this method to access the stylesheet:

var styleSheet = document.getElementById('mycss').sheet;

I personally have not attempted this, but rather followed the guidance provided in the specifications.

Answer №2

Instead of directly accessing the stylesheet for font size, consider dynamically adjusting it with this simple function:

function adjustFontSize(elementID, adjustment) {
    var targetElement = document.getElementById(elementID);
    var currentSize = parseInt(targetElement.style.fontSize, 10);
    var newSize = currentSize + adjustment;
    targetElement.style.fontSize = newSize + "px";
}

Your current approach may be trying to fetch style information from an external CSS file, but it's not doing so correctly:

document.getElementById('mycss').href
retrieves the URL string of the stylesheet, not its contents. To properly access and manipulate styles, utilize document.styleSheets - check out a useful tutorial here.

In essence, obtain the stylesheet object through document.styleSheets[index] and apply CSS rules using this.addRule().

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

Adding Jade template variable to an inline function

Trying to implement the JSCharts library. block content | <div id="chartcontainer">This is just a replacement in case Javascript is not available or used for SEO purposes</div> script. var myData=new Array() var myData = new Array([10 ...

Ensure that the Nivo Slider height is set to the accurate final value before the images finish loading

I've integrated Nivo Slider into my responsive website to display an image gallery. The slider spans 100% width and adjusts its height based on the aspect ratio of the images (all images have the same height). However, if the user's connection i ...

Unusual JavaScript Bug: Uncaught TypeError - Unable to access property 'url' of null

I encountered a peculiar JavaScript error. The following message appears in the console: Uncaught TypeError: Cannot read property 'url' of null (Line 83) The code on Line 83 looks like this: var image = '<img class="news_image_options ...

Verify the functionality of JavaScript to ensure it is enabled and functioning properly

I have experimented with various methods to determine if JavaScript is enabled and running correctly. Typically, I would use a simple test like this: $('.jstest').html('JavaScript works.'); <p class='jstest'></p> ...

Activate an iframe upon changing the media query

I am currently working on a webpage where I have included an image within an iframe. I am looking to change the content displayed inside the iframe based on different media query breakpoints. For instance, if the viewport has a minimum width of 900px, I ...

Having trouble getting my HTML file and CSS styles to render properly in Chrome

Currently, I am in the process of developing a website and facing challenges with displaying CSS properties accurately. Despite seeking input from friends and users, my HTML file is not rendering as expected within various browsers such as Chrome, Edge, an ...

What is the right way to nest a SCSS rule for a specific selector within a list using the "&" symbol?

I have a question that I couldn't find the answer to in any documentation or on Stack Overflow. While this example may not be perfect, it should give you a basic understanding of what I'm trying to achieve. Illustration .btn-group { .btn ...

What strategies can we implement to ensure consistency in visual styles and templates across our microservices?

Our team is currently working on multiple microservices simultaneously. While traditional microservice architecture discourages code sharing and reuse between services, we are considering the benefits of consistent styling across all services that have Web ...

Attempting to create a tracker that increments every time a form input field is filled out using React in conjunction with Formik

I am attempting to develop a function that will increase every time a user enters information into a field. Within my existing setup, I have a parent component with a state containing a counter value initialized to 0. My child component is a Formik contai ...

Incorporating and designing a side button using jQuery Mobile

I'm working on adding a button to the left side of the screen that is round (but not necessarily) and partially visible, with a visually appealing design. This button will allow users to open a side menu panel. Below is the HTML code for the button: ...

Unable to control audio playback in Android WebView

My Android application features a Web View component. In this Web View, I have incorporated the following HTML code to showcase an audio player: <audio controls="" preload="none"><source type="audio/mpeg" src="test.mp3"></audio> Eve ...

Tips for displaying the number of selected values in a select box label (e.g. Choose an Option)

I am currently using the jQuery multiselect API in my application to allow users to select multiple values. However, I am facing an issue where I need to fetch all the selected values when a button next to the multiselect box is clicked. Unfortunately, I h ...

Issue with VueJS/Nuxt: When using this.$router.push, the wrong template is being returned to the <nuxt-link> tag

Currently, I'm developing a search feature that takes the value from a select box and sends the user to the appropriate page. However, there seems to be an issue where the wrong template is being called upon rendering, resulting in no content being di ...

Is it possible to perform a CSS flip animation without delay?

Trying to implement David Walsh's CSS flip effect for an image that should change to another without requiring a mouseover. Is there a way to trigger it automatically, maybe in 3 seconds? I'm new to this so any help would be greatly appreciated! ...

What is causing the infinite loop when connecting to a Node.js server with Socket.IO?

A small team of two developers is currently working on setting up a Simple Chat Server using node js and socket.io on github. After pulling my partner's changes and running npm start, I noticed that my console was repeatedly outputting "a user is conn ...

Issue with Date generation in TypeScript class causing incorrect date output

I have a simple code snippet where I am creating a new Date object: var currentDate = new Date(); After running this code, the output value is: Sat May 11 2019 13:52:10 GMT-0400 (Eastern Daylight Time) {} ...

The left side of the page is anchored with text content while an engaging carousel occupies the right half

Looking to create a section on the website that remains fixed while a carousel scrolls vertically. Once you reach the final slide, scrolling will continue on the page rather than changing the carousel slide. Want it to function similarly to the Creative s ...

The art of perfect alignment: Mastering the positioning of Material-UI Grid

This issue has been resolved Hey there, I'm currently working on a React App with Material-UI and I'm trying to center a Grid item that includes a Card along with two additional Grid items. Below is the relevant code snippet. Although the Cards ...

Maintaining my navigation menu as you scroll through the page

I've been working on creating a website for my business but I'm facing a challenge. My goal is to have a fixed navigation bar that stays in place as people scroll down the page, similar to what you can see on this website: (where the navigat ...

Responsive Material-UI horizontal navigation bar

Hey there! I'm working on developing a UI using Material-UI, and I want to make it so that the menu can be collapsed into a slide-in style menu when accessed on a mobile device. Currently, I'm using tabs which allow for sliding left and right, b ...