Modifying the styles of every element on a webpage with JavaScript

I'm seeking the most effective method to dynamically update a stylesheet using JavaScript. Currently, I am aware that this can be achieved with querySelectorAll(), which retrieves all elements on a page that match a specific query. However, one drawback of this approach is that if new elements are added to the DOM, their styles must be manually replaced, leading to a messy situation.

It seems that document.styleSheets might hold the key to my issue, but I am struggling to find a straightforward way to locate and modify CSS rules or properties. While it provides functions like insertRule and addRule, I'm uncertain about how to utilize them effectively for replacing CSS properties.

Any assistance on this matter would be greatly appreciated!

PS: While I prefer utilizing JavaScript for this task, I am open to using jQuery as well. I can always figure out a way to convert jQuery code to JavaScript.

Background: I frequently use websites like waffle.io and am not satisfied with their themes. In an attempt to customize these sites using a Chrome Extension and JavaScript, simply changing HTML attributes isn't sufficient since waffle.io regularly updates its DOM. My goal is to run a script once at the start and ensure that newly added elements also adhere to the updated styles. Given this constant DOM changes, I believe updating CSS rules/properties within the stylesheet itself is crucial (although I could be mistaken).

If my objective is still unclear, please don't hesitate to let me know.

Answer №1

If you're looking to achieve a specific override in your HTML code, one approach could be to add a unique class to the html tag and then manipulate it with JavaScript.

By default, your html tag could look like this:

<html class="default">
...
</html>

Then, with JavaScript, you can easily update the class to include additional styles:

<html class="default updated">
...
</html>

In your CSS, you can target specific elements based on these classes:

.default .element { /* default styles */ }
.default.updated .element { /* updated styles */ }

By using this method, the "updated" class will take precedence over the "default" class due to its higher specificity. This can be a simple way to apply changes to all elements on the page using both JS and CSS together.

I hope this explanation is helpful for your needs!

Answer №2

It appears there may be some confusion regarding your intentions, but you have the ability to modify the src attribute of an external style sheet using JavaScript.

Answer №3

Implementing a similar approach is achievable. The font size for all elements can be modified, along with other properties as needed.

You have the option of either assigning a class to the html element or directly applying a property to the html element within the CSS.

<!Doctype html>
<html>
  <head>
    <style>
      html {
        font-size: 10px
      }

      * {
        font-size: 1rem
      }

      .first {
        font-size: 1.2rem
      }

      .second {
        font-size: 1.5rem
      }
    </style>

    <script>
      function adjustTextSize (key) {
        const textSize = key === 'small' ?  '10px' : '16px'
        document.documentElement.style.fontSize = textSize
      }
    </script>
  </head>
  <body>
    <button onclick="adjustTextSize('large')">+</button>
    <button onclick="adjustTextSize('small')">-</button>
    <p class="first">
      The constraints parameter is a MediaStreamConstraints object with two members: video and audio, describing the media types requested. Either or both must be specified. If the browser cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with NotFoundError.
    </p>

    <p>
      The constraints parameter is a MediaStreamConstraints object with two members: video and audio, describing the media types requested. Either or both must be specified. If the browser cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with NotFoundError.
    </p>
  </body>
</html>

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

Strange Behavior of SVG 'fill: url(#....)' in Firefox

I am struggling with an SVG graphic that I have created. Here is the code: <svg width='36' height='30'> <defs> <linearGradient id="normal-gradient" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" s ...

Using *ngIf and *ngFor in Angular to switch between divs depending on their index values

Is there a way to toggle between two divs based on the index value using *ngIf in Angular? I have attempted to do so by toggling boolean values of true and false, but my current approach is not working. Here is what I have tried so far: <div *ngFor=&qu ...

A more efficient method for refreshing Discord Message Embeds using a MessageComponentInteraction collector to streamline updates

Currently, I am working on developing a horse race command for my discord bot using TypeScript. The code is functioning properly; however, there is an issue with updating an embed that displays the race and the participants. To ensure the update works co ...

Combining duplicate objects in a JavaScript array

I am looking to identify duplicates by country code and merge them into a single object The array structure is: [{...},{...}] Objects {Country_Code: "RU", Country: "Russia", Provider: "Shell1", Price: "0.123"}, {Country_Code: "EN", Country: "Russia", P ...

Getting Started with NodeJS Child Process for Electrons

My current challenge involves integrating a Gulp setup with debugging electron-quick-start. I am attempting to close and reopen Electron when changes are made to my source files using child_process.spawn. Launching the application seems to work fine, but w ...

Guide to refreshing a page (state) in a react application

As I delve into learning react.js, I decided to develop a basic rock paper scissors game within a react app. However, I've encountered some difficulty in creating a reload button that differs from the standard JavaScript button implementation which ty ...

Adjusting a polyline in Google Maps

I've successfully used Google Maps V3 API to create a polyline with 2 points. However, I now need to shorten the polyline. Issue: My goal is to make the polyline extend from the start point to the midpoint between the start and end points. How can I ...

Passing a querystring value to a Vue.js component

I am encountering an issue with passing a value from a querystring to my Vue component. The querystring looks like this: https://someurl.com?q=test My component is structured as follows: Vue.component('externalrecipes', { props: ['results&a ...

Adding an external JavaScript file to an Angular 5.0.0 project

Struggling to integrate hello.js into my Angular 5.0.2 project. See the CLI version below https://i.sstatic.net/RcGz5.jpg I have included the script file in angular-cli.json. "scripts": [ "./js/hello.js", "./js/hello.polyfill.js", ...

a height of 100% with a minimum height of 100%

Is there a way to make the third and fourth rectangles have the same position while filling all the remaining height in %? Keep in mind that we can't change the min-height:100% on the body or html. Feel free to use CSS and HTML for your code solution. ...

Error encountered: Attempting to change the mode of THREE.TransformControls, but THREE.TransformControls is not defined

I've been working with the TransformControls package (you can find it here: https://github.com/lucascassiano/three-transform-controls). While the transform controls appear to be functioning mostly fine, they are causing two major issues in my applicat ...

Having difficulty applying parseFloat directly following a JSON Stringify operation

There's a specific line of code I'm working with that reads -- let longitude = JSON.stringify(place.lon); After calling alert(longitude), I receive the output "44.54321". However, my intention is to retrieve just the number itself, so I attempt ...

Angularjs is struggling to connect data to the user interface

It seems that the array is not binding properly in the UI. In the HTML code, I am using dataTables. The variable $scope.successMessage is also not binding to the UI. I have tried multiple approaches but none seem to be working. Here is a snippet of th ...

Overlay one image on top of another

Recently, I've been working on this code snippet. I am attempting to center the profile picture even when the screen width is reduced. The issue lies with using position:absolute, preventing margins:auto from functioning properly. As a workaround, I ...

How can you determine if a polymer element has been loaded or not?

element, I am interested in dynamically importing elements using the Polymer.import( elements, callback ) method. The callback is triggered only if the elements have not been imported yet, indicating they are already loaded. My query is: Is there a conve ...

Javascript Workers - how can I improve the handling of worker messages and address any delays?

I have a situation where a Worker is sharing a SharedArrayBuffer with the main thread. In order for everything to function properly, it's crucial that the worker has access to the SAB before the main thread tries to access it. (EDIT: The code creating ...

A guide to spinning an image in every direction with CSS

I'm working on rotating an image in all directions using CSS and Vue.js. To demonstrate this, I have created a CodePen with the necessary code below. <div id="app"> <v-app id="inspire"> <div class="text-xs-center image-rotation" ...

Angular throws a 404 error when making a JSONP http request

I've been incorporating Mailchimp integration into an Angular application. For using it in pure JS, I retrieved the code from the embedded form on the Mailchimp site: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js ...

Failure occurred when attempting to link and display on the page container

I have created a simple app using jQuery Mobile. At some point in the app, I include the following code: <a href="test_es.html" data-role="button">Start!</a> This code snippet loads a new HTML file that contains several jQuery Mobile page ...

Tips for blocking the insertion of "Emoji & Symbols" into an input field

Currently, I am utilizing Vue JS, but I am willing to consider vanilla JS suggestions as well since they both serve the same purpose. My objective is to block default emojis from being inserted into a text field through either the IOS keyboard or the (CMD ...