Guide on using JavaScript to implement the universal CSS selector

One technique I frequently employ is using the CSS universal selector to reset the dimensions in my HTML document:

* {
    border: 0;
    margin: 0; 
    padding: 0; 
}

I wonder if a similar approach can be achieved with JavaScript as well?

When it comes to regular HTML elements, we have the style property. But how can we target the universal selector using JavaScript?

Answer №1

querySelectorAll("*") retrieves all elements within the DOM. You can then apply styles to each element in the selection:

var allElements = document.querySelectorAll("*");
for (var i = 0, length = allElements.length; i < length; i++) {
    var item = allElements[i];
    // item.style.border = ...
}

Answer №2

To optimize the process, you can delegate this task to the CSS engine of your browser without iterating through all elements. Here's an example:

;(function(exports) {
  var style = document.querySelector("head")
                      .appendChild(document.createElement("style"));

  var styleSheet = document.styleSheets[document.styleSheets.length - 1];
  styleSheet.insertRule("* {}", 0);

  exports.universal = styleSheet.cssRules[0];
}(window));

Now, you have a window.universal object that allows you to style all elements easily. For instance:

window.universal.style.border = "1px solid red";

No need to dynamically create the <style> tag every time. You can include it in the HTML structure as well.

You can test it by executing this snippet:

;(function(exports) {
  var style = document.querySelector("head")
                      .appendChild(document.createElement("style"));

  var styleSheet = document.styleSheets[document.styleSheets.length - 1];
  styleSheet.insertRule("* {}", 0);

  exports.universal = styleSheet.cssRules[0];
}(window));

console.log("universal" in window); // true

window.universal.style.border = "1px solid red";
<div>
  Hello
  <span>World</span>
</div>

Answer №3

To achieve this in vanilla JavaScript, you can use the following code snippet:

document.querySelectorAll('*')

However, I would advise against applying CSS styles to all elements using JavaScript.

Answer №4

A big shoutout to VisioN for sharing this helpful solution! Another great alternative is using the JavaScript Query Selector API:

var allElements = document.querySelectorAll('*');

for (var j = 0; j < allElements.length; j++) {
  var selectedElement = allElements[j];        
  selectedElement.style.border = '0px';
  selectedElement.style.margin = '0px';
  selectedElement.style.padding = '0px';
}

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

Using an Ajax Post request to trigger a JavaScript function

Looking to execute a JavaScript function with a PHP variable, I utilized an AJAX request to send the variable named [filename] for executing the JavaScript function as follows: upload.php <script> function prepareforconvert(filenamse){ ...

Using AngularJS variables within JavaScript code

This is my introduction to using AngularJS. The code snippet below displays the desired output: <a href="http://www.example.com/xyz/{{life.animal}}/" target="_blank">Hello </a> Upon clicking, it redirects to: http://www.example.com/xyz/c ...

When attempting to retrieve data in a server-side component, Next.js encountered an ECONNREFUSED error with ::1:3000

import React from "react"; import axios from "axios"; interface UsersType { id: string; firstName: string; lastName: string; email: string; } interface dataProps { allUsers: UsersType[]; } async function getData() { try { c ...

Struggling to understand JSON in joint.js?

I am trying to utilize the joint.js library to render a JSON data as a chart... let paper = new joint.dia.Paper({ el: $('#paper'), width: 600, height: 200, model: graph }); let graph = new joint.dia.Graph; let json = '{"em ...

The most basic form of req.body will consistently be devoid of any content

I am currently working on passing basic data from the client to the server using a POST request for testing purposes. However, I am encountering issues with receiving empty or undefined logs on req.body. Server: //jshint esversion:6 const express = requi ...

Tips for incorporating border/outline/stroke into SVG elements using CSS

Currently, I am incorporating SVG elements into a webpage using D3js. However, I am facing challenges when it comes to styling these elements as typical CSS syntaxes like path { border: 3px solid green; } do not seem to work. Is there a way to apply bo ...

Creating personalized hooks that rely on React query requests

Utilizing a series of custom hooks, I am able to fetch data and perform various calculations based on that data. One particular hook calculates the total amount that should be set aside monthly for future expenses, using the output from previous data-fetch ...

The <img> tag is displaying with dimensions of 0 x 0 pixels even though its size was specified

Is there a way to control the image size within an <img> tag placed inside an html5 video element? Currently, it keeps defaulting back to 0 x 0 pixels. The reason behind using this img is to serve as a fallback for outdated browsers where the video ...

What is the method for including a dynamic image within the 'startAdornment' of MUI's Autocomplete component?

I'm currently utilizing MUI's autocomplete component to showcase some of my objects as recommendations. Everything is functioning correctly, however, I am attempting to include an avatar as a start adornment within the textfield (inside renderInp ...

What are some cookie serialization techniques in JavaScript and PHP?

I have a form with multiple select options that I want to save in a cookie for user convenience. The goal is to make the serialization of the cookie easily readable in both JavaScript and PHP, allowing me to set the form onLoad and filter search results ba ...

Every time I attempt to build a React application, I encounter the same error message. I even checked the log file, but it keeps showing the proxy error

An error occurred in the command prompt while installing packages. This process may take a few minutes. Installing react, react-dom, and react-scripts with cra-template... Error: ERR_SOCKET_TIMEOUT The network encountered a socket timeout while trying to ...

Compatibility issues between jQuery and AngularJS are causing problems

Currently, I am facing a compatibility issue between RequireJS and Angular in my setup. Everything functions without any problems when using jQuery version 1.7.2. However, I wanted to upgrade to jQuery 1.8.1 along with jQuery UI, but unfortunately, my Angu ...

Using the max-width property with Semantic UI Dropdown in ReactJS

I'm struggling to determine how to adjust the max-width of the Dropdown element in ReactJS. I attempted the following: .Menu Dropdown { max-width: 5rem !important; } Unfortunately, this did not work as expected. The dropdowns are taking up too m ...

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

What is the best way to send multiple input box values to a function set in the controller?

I am attempting to send the values of two input boxes to a single controller function. <div class="container" ng-controller="MainCtrl"> <div class="row"> <div class="col-lg-6"> <input type="text" ...

What is the best way to implement a dropdown in MUI and React that displays functional components as items?

Here is a list of dummy components: const OwnerList = () => { return ( <Box sx={{ display: 'flex', }} className="owner-container" > <Avatar src='https://hips.hearstapps.com/hmg- ...

Issue with Java Script inheritance in google.maps.OverlayView not functioning as expected

UPDATE: After spending another day working on this, I believe I have identified the issue, although it is not yet confirmed. Once I have verified the solution, I will update this post with an answer. My current understanding is that the problem arises fro ...

Memory leakage in Internet Explorer as a result of JavaScript code

Recently, I created a website that utilizes jquery ajax to send an ajax request every minute in order to retrieve json data. This data is then parsed and added into the DOM. While this process runs smoothly on Chrome and Firefox, I noticed a significant m ...

Can you explain the concept of peer dependencies and plugins to me?

After reading numerous articles and posts on the topic of peer dependencies, I still find myself struggling to fully understand the concept. For instance, if coffee 1.0 has a dependency on milk 1.0, then logically coffee 1.0 would be included in my packa ...

Encountering a Type Error in React Native when attempting to create a 3D cube with Three.js

Following a tutorial on creating a simple app that displays a 3D cube, I encountered an issue with my code: import React from 'react' import {View} from 'react-native' import Expo from 'expo' import {Scene, Mesh, MeshBasicMate ...