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

Creating a Custom Rule for Checkbox Validation using jQuery

Can the jQuery Validation plugin be used to validate custom values on checkboxes, rather than just True or False? For instance: <input id="test" type="checkbox" name="test" value="something"> I am struggling to find a method that can check if &apo ...

AngularJS- numerous unique directives featured on a single page each with its distinctive state

Regarding the query about Calling a method in a directive controller from another controller. Is there a way to have multiple separate directives of the same type on a page? Since they share a common API (singleton), the state is also shared. Therefore, i ...

AngularJS retrieve data from JSON (like using MySQL)

My data is in JSON format: {"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","u ...

Exploring textboxes with jQuery loops

Is there a way to clear all these textboxes by iterating through them using Jquery? <div class="col-md-4" id="RegexInsert"> <h4>New Regex Pattern</h4> <form role="form"> <div class="form-group"> &l ...

When a form added by jQuery is submitted, the associated JavaScript does not run as expected

After clicking a button on my page, jQuery removes one form and replaces it with another. However, when I try to submit the second form, the associated JavaScript does not execute as expected. Instead of running the JavaScript function, the form submissio ...

What causes certain components in ReactJs to not respond to the `:focus` pseudo-class?

Currently, I am in the process of implementing a straightforward Emoji-Rating system where 5 emojis are displayed on the screen and upon hovering over them, their appearance changes. This functionality is achieved using the :hover pseudo-class. My goal is ...

Limiting overflow:visible to input and select fields only

I'm currently facing an issue with a Lightning Web Component in Salesforce, however, I believe the root cause of this problem is not specific to this platform. Within my container div, I have row divs displaying select/combobox fields that need to ex ...

Encountering a hiccup during a join linq query操作oops!

I am currently working on this code snippet: public ActionResult JoinSupToPro() { SupplierDBContext dbS = new SupplierDBContext(); var innerJoinQuery = from pro in db.Products join sup in dbS.Suppliers on pro.SupplierId equals sup ...

Excessive HTML and CSS overflow stretching beyond the boundaries of the page on the right

It seems like the issue lies with div.ü and div.yayın, as they are causing overflow on the right side of the page. When these elements are removed, the overflow issue goes away. Are there different positioning codes that can be used to prevent this? d ...

Prettyprint XML in Angular 8+ without using any external libraries

I am working with Angular 8+ and I need to display XML content in a nicely formatted way on my HTML page. The data is coming from the backend (Java) as a string, and I would like to present it in its XML format without relying on any external libraries or ...

The HTTP request is being executed twice for some reason unknown to me

import React, {useState, useEffect} from 'react' export function UseStateExample() { // This is a named export that must be used consistently with {} when importing/exporting. const [resourceType, setResourceType] = useState(null) useEffect ...

Leverage the retrieved JSON data from the database within an HTML template using the Play

Currently, I am facing a challenge with implementing a login feature in my project. I am struggling to figure out how to showcase the JSON string that is returned on the webpage. Below is a snippet of my code: Security.java: public Person webLogin(Perso ...

How can an array be concatenated using tabs?

I am currently in the process of integrating with an old system that requires a value to be sent via a GET request as a tab delimited string. I have my data stored in an array, but I am facing difficulty when attempting to properly format it using the join ...

Transferring Data Between Two Forms

Is there a way to transfer data between two HTML forms? For example, let's say we have two forms: Form 1: Contains a field for name and a submit button. Form 2: Contains fields for name, email, and a submit button. I would like to be able to fill o ...

The execution of ajax within a script being called by another ajax request is not functioning as expected in PHP

I am currently working on a project that involves three files, each serving a specific purpose as outlined below: //File1.php $('button.button1').click(function(e){ $.ajax({ type: "POST", url: "file2.php ...

Automatic capitalization of menu options in Bootstrap dropdown

Is anyone else curious about why the menu items are in all caps while the markup is in lower case? What steps can be taken to prevent this from happening? https://i.stack.imgur.com/S86RO.png ...

jQuery does not support animations for sliding up or down

I'm struggling to conceal a navigation element once the top of the #preFooter section is scrolled to. In order to make the nav element mobile-friendly, I have designed both the .tab-wrap and .tab-wrap-mobile. To enable these elements to slide away w ...

The precision of the css function in jQuery

Possible Duplicate: jQuery and setting margin using jQuery In the HTML snippet below, I have set margins for a paragraph element to center it: <p style="margin-left:auto; margin-right:auto; width:200px;">Hello</p> After that, I attempted ...

Personalized JSON response type for AJAX requests

Do you think it's possible to achieve this? I have an idea to create a unique dataType called "json/rows". This new dataType would parse the server output text and manipulate it in some way before passing it to the success function. What do you think ...

What is the best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class. interface IQuiz { quizProg: TypeQuizProg; qidx: number; state: IStateCtx; actions: IActionsCtx; } @observer class Comp extends Rea ...