Ways to adjust the height of an element using the ::before selector in javascript

Within the realm of styling, there exists an element adorned with the .bg class. Its aesthetic instructions are described as follows:

.bg {
    width:100%;
}

.bg:before {
    position: absolute;
    content: '';
    background: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
}

Moreover, there exists a JavaScript directive that mandates the height of the .bg class:

$(".bg").height($(document).height());

However, the objective is to assign the height of $(document).height() to .bg:before instead. How can such a task be accomplished using JavaScript? This is because the code

$(".bg:before").height($(document).height());
does not yield the desired outcome.

Your guidance and assistance are greatly appreciated

Answer №1

With the power of JavaScript, you can tweak the rule for .bg:before in a clever manner.

By looping through the style rules in the stylesheet, you can identify if the current rule corresponds to .bg:before (r.selectorText == .bg:before). If it does, you can dynamically adjust its height property (

r.style.height = window.innerHeight + 'px'
).

var styleSheets = document.styleSheets;

for (var i = 0; i < styleSheets.length; i++) {
  var rules = styleSheets[i];
  for (var j = 0; j < rules.cssRules.length; j++) {
    var rule = rules.cssRules[j];
    if (rule.selectorText == ".bg:before" || rule.selectorText == ".bg::before") {
      console.log('Previous rule: ' + rule.cssText)
      rule.style.height = window.innerHeight + 'px';
      console.log('Revised rule: ' + rule.cssText)
    }
  }
}
.bg {
  width: 100%;
}
.bg::before {
  position: absolute;
  content: '';
  background: rgba(0, 0, 0, 0.5);
  width: 100%;
  height: 100%;
}

Answer №2

It's impossible to achieve with JavaScript since pseudo-elements do not exist within the DOM structure.

Answer №3

By passing a value into the pseudoelement from the main element through a CSS variable, you can access the main element via javascript to calculate and update that value. To ensure a fallback value is used until the value is updated, you can set a default value for the CSS variable in any parent element's CSS (such as 100% in this example).

In code, you can achieve this by using height: var(--bg-height, 100%); in the pseudoclass and then utilizing

element.style.setProperties('--bg-height',document.body.scrollHeight+'px');
in your javascript.

It's worth noting that when using vanilla js – like in this case – in 2022, there may be some box-model peculiarities with certain methods of calculating document height.

See below for a full working example:

let el = document.getElementById('example');
el.style.setProperty('--bg-height', 
    document.body.scrollHeight+'px');
/*************************************************
  The CSS from the question.  I lightened the grey 
  (dropped the transparency from 0.5 to 0.25) and 
  added a var for height.
 ***/

.bg {
  width:100%;
}

.bg:before {
  position: absolute;
  content: '';
  background: rgba(0,0,0,0.25);
  width: 100%;
  height: var(--bg-height, 100%);
}


/*************************************************
  Following is for this demo and can be removed.
 ***/

:root {
  font: 16px Roboto, Helvetica, Barlow, sans-serif;
}
body {  
}
a { color: #435; }
section>p {
  max-width: 600px;
  margin: 1rem auto;
}
<section class="bg" id="example">
  <p>Here is a section that is the main element being focused on. It has a transparent (thus, white) background.  There is a :before pseudoelement positioned absolutely over it with a highly transparent black (thus a light grey tint).  Using javascript, this pseudoelement is set to a height equal to the document itself.</p>
  <p>Resizing and other things that would change the document height should be taken into account and observed.</p>
  <p>Answer to <a href="https://stackoverflow.com/questions/27358143/how-to-set-height-to-an-element-with-before-selector-with-javascript">How to set height to an element with ::before selector with javascript?</a></p>
</section>

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

Utilize CSS block display for ::before and ::after pseudo elements within a div container

I have a CSS file that contains the following code snippet: .loader { width: 250px; height: 50px; line-height: 50px; text-align: center; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-fam ...

Saving the information into a designated MongoDB repository with a particular title

One of my recent projects involved creating a script that pulls data from the Binance API and sends it to MongoDB. This script runs every hour using the Node-Schedule package, fetching three different sets of data based on their symbols (BTCUSDT, ETHUSDT, ...

Guide to installing a dynamic favicon on a Next.js application for a specific route

I am trying to set up different favicons for my Next.js app based on the route. Here is where I want to implement this feature, displaying the country's flag as the favicon when a user navigates to that specific page. Below is the code snippet from m ...

Is it possible to transmit a WebRTC frame to a Python script?

I recently built my first web app using Python and Django, which displays webcam frames of clients. 'use strict'; // For this project, I am only streaming video (video: true). const mediaStreamConstraints = { video: true, }; // Video element ...

What are the consequences of submitting a form to a different website through POST method?

Dealing with a CMS that does not offer an easy way to add a NodeJS route for handling form data can be quite challenging. I'm considering the following setup - would this be considered bad practice or unsafe? Server 1 (Ghost CMS) : www.domain.com &l ...

The xhr.upload event listener is triggered when the xhr.responseText is empty after loading

const request = new XMLHttpRequest(); request.open('put', url, false); request.upload.addEventListener('load', function(e) { alert(request.responseText); }, false); Why is the responseText property of the XMLHttpRequest object empt ...

What is the best way to customize the endIcon of a styled-component button?

Presented here is a neatly styled button I've created import styled from 'styled-components'; import Button from '@material-ui/core/Button'; import ArrowForwardIosIcon from '@material-ui/icons/ArrowForwardIos'; const MyB ...

JS: Decreasing the counter while calling the hide() function

If I have a standard count <?php echo "Today (".mysql_num_rows($query)."); ?> It will display as Today (10) if there are 10 entries. Beneath this counter is a while() loop that displays all the rows in a <tr>. Within each <td> in the ...

What methods can be used to maintain the selected date when the month or year is changed in the react-datepicker component of reactjs?

At the moment, I am using the Month selector and Year selector for Date of Birth in the react-datepicker component within a guest details form. The current functionality is such that the selected date is highlighted on the calendar, which works fine. How ...

Alignment issues with Navigation Elements

Recently, while working with the Bulma CSS framework, I encountered an interesting challenge. I wanted to align the navigation buttons to the bottom of the red field, but they appeared to be shifted out of alignment. Despite trying to apply inline CSS styl ...

Tips for attaching inline styles to the body element with a vuejs component

I am new to vue.js and have been learning for a couple of days now. There are still some concepts that I am struggling to understand. I am currently working on creating a dropdown menu that appears when the user clicks on three dots. However, I am facing a ...

The mathematical logic behind navigating forward and backward in Angular

Calling all math experts! I need your help with a slider issue. The prevSlide function is working perfectly, but the nextSlide function seems to be starting off on the wrong foot. It goes 1-2-3 and then jumps to 2-3-2-3... It's definitely a math probl ...

When the user modifies the input, React fails to update the component state

Currently, I am utilizing React in conjunction with express to server-side render the views for my project. However, I have encountered a minor setback. Within one of my components, users are directed after their initial login. Here, they are prompted to ...

What is the best way to refresh my Material-UI checkboxes following updates to certain states in a React JS environment?

One of my latest projects involves an application that visualizes graphs, with all nodes originally colored blue. I included a component in the form of a checkbox that users can interact with to trigger a state change. This change dynamically alters the co ...

refers to the spacing between elements

I currently have 4 nested divs. My goal is to ensure that the margins between each div are equal, maintaining the same distance from the left edge of the parent div to the first nested div, between each pair of nested div, and from the last nested div to t ...

How can I troubleshoot email validation issues in Vue.js?

<button type="submit" class="register-button" :class="(isDisabled) ? '' : 'selected'" :disabled='isDisabled' v-on:click=" isFirstScreen ...

Modifying modal content disrupts AJAX events

When using jquery-ujs for ajax requests with data-remote="true", I encounter an issue where the first request goes smoothly but subsequent ones break. It seems that when certain events like $('#modal').empty(), $('#modal').tex ...

Apply the style when the page loads and remove it when clicked

There is a feature in my code that adds a class when an element with the class .tab is clicked. $(function() { $(".tab").click(function() { $(this).addClass('blueback'); $(".tab").not($(this)).removeClass('bl ...

How can you alter a property within an array of records retrieved from a Mongoose query?

const images = await tbl .find({ creator_id: req.user._id, }) .select({ creator_id: 0, }) .exec() .then((images) => images.forEach((image) => { image.file_name = process.env.IMAGE_ ...

Steps for bundling a Node server with an Electron application

I am looking to package my Electron app, built with React.js, along with a local Node server into a single executable file. Is there a way to ensure that the separate Node server runs simultaneously with the Electron app when the program is executed? ...