Can the value of a CSS class be obtained even if it is not being used?

I have an application that pulls data from a database and displays it with associated metadata that dictates the display style. Let's simplify it and say the only metadata is the size of the square it should appear in. For example:

dataArray : {
    {squareSize: "squareSize1", value:"foo"},
    {squareSize: "squareSize3", value:"bar"},
    {squareSize: "squareSize4", value:"oof"},
}

HTML:

<div id="dataGrid" class="grid">
</div>

CSS:

.squareSize1 { height: 100px; }
.squareSize2 { height: 200px; }
.squareSize3 { height: 300px; }
.squareSize4 { height: 400px; }

JAVASCRIPT:

document.ready(function() {

    // ...  //
    // 
    // {squareSize : "squareSize4", value: "foo"}
    dataArray.forEach((data, index) => {
        let html =  "<div id=" + index 
        html += " class=\"" + data.squareSize + "\" >" 
        html += data.value + "</div>"
        $dataGrid[0].innerHTML += html; 

        // logs the height of the div 
        // i.e. if data was of type "squareSize4" : 400
        console.log($("." + data.squareSize).height());             
    });
}

Later in the code (not in the document.ready() I have a way for users to add content from the same kind of data. Issue is, if an element of the same CSS class doesn't already exist, I can't get the height:

// I have elements of class squareSize1 and squareSize3:
console.log($(".squareSize1").height());  // 100
console.log($(".squareSize2").height());  // undefined
console.log($(".squareSize3").height());  // 300

Same results with .css('height'):

// I have elements of class squareSize1 and squareSize3:
console.log($(".squareSize1").css('height'));  // 100px
console.log($(".squareSize2").css('height'));  // undefined
console.log($(".squareSize3").css('height'));  // 300px

QUESTION: Can I retrieve the value of 200 from my CSS if I don't have any elements of squareSize2 in my DOM yet?

P.S. I need this value for some advanced UI functionality

Answer №1

Is it feasible to retrieve the value of 200 from my CSS even if there are no elements with the class "squareSize2" in the DOM yet?

It is not achievable without manually parsing the CSS rule, which can be accessed by exploring the object tree in document.styleSheets.

However, you can temporarily insert an element with that class, retrieve its css("height"), and then remove it:

const div = $("<div>").addClass("squareSize2").appendTo(document.body);
const height = div.css("height");
div.remove();
console.log(height);
.squareSize1 { height: 100px; }
.squareSize2 { height: 200px; }
.squareSize3 { height: 300px; }
.squareSize4 { height: 400px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

JavaScript equivalent code to C#'s File.ReadLines(filepath) would be reading a file line

Currently in my coding project using C#, I have incorporated the .NET package File.ReadLines(). Is there a way to replicate this functionality in JavaScript? var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray(); I am a ...

Transforming font sizes in mobile dp units to desktop px measurements

Yes, it's true - using px in css for specifying font-size is not ideal. However, in my case, I have a unique situation. I am currently developing a browser-based editor that is specifically designed for creating mobile content visually. The editor fe ...

Returning a button to its original state

Currently, I am working on styling the video controls on my website and have run into a small issue. The video section consists of a video list and a video player. When an li element from the list is clicked, the source of the video player changes to the ...

I'm having trouble getting my jQuery to connect with my HTML, no matter what I do

UPDATE: Thank you everyone, I finally figured out that it was the API causing the issue. Even though I downloaded the files to avoid server requests, I will switch to using https instead. I have a couple of questions. Why isn't my code functionin ...

What strategies and techniques should be considered when creating websites optimized for mobile devices?

With a wealth of experience in programming languages like Java, Python, and C, I actively engage in self-study to enhance my skills. While I have dabbled in creating mobile-friendly websites, upon reviewing my work, it is evident that my frontend developme ...

Establish a vertical column that matches the height of its parent element

Is there a way to create a column that matches the height of its parent element? I have a navbar followed by a container with three columns. The challenge is to make the last right column the same height as its parent and also scrollable. In this scenario, ...

Retrieval is effective in specific situations but ineffective in others

I have encountered an issue with fetching data only when using the async behavior. I am currently in the process of re-building a property booking website that was originally developed using Laravel and a self-built API. The new version is being created wi ...

Error: The absence of type definition

I am struggling to implement the functionality of an Add Question button, encountering an error message that reads: TypeError: form.questionText is undefined Can anyone point out where I went wrong? <script type="text/javascript"> fun ...

Ensuring the server application is up and running before initiating the mocha tests

This is similar to Ensuring Express App is running before each Mocha Test , but the proposed solution isn't effective + I am utilizing a websocket server In essence, I'm making use of a websocket framework called socketcluster and this represent ...

Chrome does not support top.frames functionality

I have three HTML pages: main.html, page1.html, and page2.html. I am displaying page1.html and page2.html within main.html using the code below. <!DOCTYPE html> <html> <frameset frameborder="1" rows="50%, *"> <frame name="f ...

Using the Moment library in a NestJS application

I am integrating momentjs into my nestjs application and I want to ensure that my services can be tested effectively. To achieve this, I have included momentjs in my module setup as shown below: providers: [ { provide: 'MomentWrapper', ...

Assign the ng-repeat item to a variable in the controller's scope

Can anyone help me figure out how to pass a particular item from my view to a function in my controller? Here is the code: The view where I want to pass p.id <tr ng-repeat=" p in projetsListe"> <td>{{p.NomProjet}}</td> <td>{{c ...

I attempted to publish my React application using gh-pages and encountered the following error: "The argument for 'file' must be a string. However, it was received as undefined."

I encountered an issue while attempting to deploy my React application with gh-pages. The error message I'm facing states: "The 'file' argument must be of type string. Received type undefined." Initially, I suspected that the problem was wi ...

Use a text link to upload a file instead of using an input field

While I've seen some discussions on this topic already, the conflicting answers have left me uncertain. Is there a foolproof method for triggering file upload without using an input field? Essentially, I'd like to create a div with an icon and te ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

"Utilizing JavaScript to filter JSON data at a deep nested

When working with a JSON data set, I often face the challenge of filtering based on specific child values. Take the following example: [ { "Date": "2017-03-02T00:00:00", "Matches": [ { "Id": 67, ...

Issue with dat.gui not displaying correctly within a WebGL container

When attempting to display my dat.gui interface with a button and textbox on top of my WebGL window, I encounter this issue: https://i.sstatic.net/N9peP.png The section for "Close Controls" in the dat.gui is visible, but strangely the button and textbox ...

What is the best way to display JSON response data in a datatable by utilizing jQuery AJAX requests?

I am attempting to implement a date range search using jQuery Ajax and display the data in a datatable. Below is the PHP controller code I am using. public function date() { $date_from = date('Y-m-d H:i:s', strtotime($this->input->pos ...

Choose either nth-child or nth-of-type within a nested element

Here is the HTML code snippet: <div class="homepage-body"> <a href="#"> <div class="homepage-item"> <div class="homepage-icon"></div> <div class="homepage-text"> Test1 </di ...

Guide to implementing 301 redirection from HTTP to HTTPS in Next.js

What is the process for implementing a 301 redirection from HTTP to HTTPS in Next.js? One example of this would be redirecting from "http://stackoverflow.com/" to "https://stackoverflow.com/". ...