Adding CSS styles to an HTML page using JavaScript

Unfortunately, I do not have the ability to access the HTML directly as it is generated dynamically by a program. However, I do have access to the JS page that is linked to it.

As an example, I am able to manipulate elements using JavaScript like so:

window.onload=function(){
        var output = document.getElementById('main_co');
        var i=1;
        var val="";

      while(i<=1)
        {  if(!document.getElementById('timedrpact01'+i))
            {
                var ele = document.createElement("div");  ele.setAttribute("id","timedrpact01"+i);
                ele.setAttribute("class","inner");

                ele.innerHTML=" Hi there!" ;

                output.appendChild(ele);
    

I want to build upon this and add a button that can toggle between different CSS sets (there are multiple files being used) located in another path.

Thank you very much!

Answer №1

To include external stylesheets on a webpage, you can use the link element like this:

<link rel="stylesheet" href="http://example.com/path-to-css">

You can target the link element by using the following JavaScript code:

var css = document.getElementsByTagName("link")[0];

In this example, we are selecting the first link element based on its index [0].

Afterwards, if you need to update the path of the stylesheet, you can do so by changing the value of the href attribute.

css.setAttribute("href", "http://example.com/new-path-to-css");

Answer №2

 window.onload=function(){
    var result = document.getElementById('main_content');
    var counter=1;
    var value="";
   
    var changeStyles = function() {
      var elements = document.getElementsByTagName("link");
      for(var j=0; j < elements.length; j++)
         elements[j].href = elements[j].href.replace('path_to_file', '_new_path');
    };

   while(counter<=1)
   {  
      if(!document.getElementById('timedrpact01'+counter)) {
        var elem = document.createElement("div");  elem.setAttribute("id","timedrpact01"+counter);
        elem.setAttribute("class","inner");
        elem.innerHTML=" Greetings!" ;
        var btn = document.createElement('button');

        if(btn.addEventListener) {
          btn.addEventListener('click', changeStyles);
        }
        else { 
          btn.attachEvent('click', changeStyles);
        }

        result.appendChild(btn);
        result.appendChild(elem);
      }
   }
 }

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

Tips for injecting animation into a DIV

I am trying to make a <div> element on my webpage expand to the full width and height of the screen. While I have managed to achieve this, I also want to implement an animation that will be displayed when the <div> enlarges to fit the screen si ...

When does the ng-disable function become activated?

Here's an example: <button ng-disabled="!isSomethingValid() || loading || disabled" ... class="btn btn-primary"> What determines the condition for the ng-disable attribute to evaluate its expression? ...

Storing Objects in MongoDB using Node.js

I am working on an application where I need to store an object for later execution of functions. This object essentially holds the data of a cron job. var cronJobObject = schedule.scheduleJob(new Date(2018, 0, 19, 15, 15, 0), function() { console.log( ...

Why does my dialog box only open the first time and not the second time?

I have created my own custom dialog box using jQuery and it seems to be working fine initially. However, after closing it once, when I try to open it again nothing appears. Can anyone help me identify what's causing this issue? Below is the source co ...

Ways to align images of the same size in a gallery using the margin: auto property

I have an image gallery within a div element named "container" with a specified width:70%. I need the images to be justified with auto margins. This is the HTML code I am using: (There are 4 images in total) <div class="container"> < ...

"Having trouble with sound in react-native-sound while playing audio on an Android AVD? Discover the solution to fix this

react-native-sound I attempted to manually configure react-native-sound but I am unable to hear any sound. The file was loaded successfully. The audio is playing, but the volume is not audible on Android AVD with react-native-sound. ...

What is the accurate method of sending form data to the SQL database?

This is the data submission form I am using: <p align="center" style="color:#F00;"> <?php echo $msg; ?> </p> <form class="form-horizontal style-form" name="form1" method="post" action="Create-jobs.php" onSubmit="return validate(); ...

What is the proper way to encode URL parameters for a REST API request?

When working on a REST API call, I needed to create some URL parameters using Angularjs 1.4.2. To achieve this, I utilized a form to pass the parameters to a service function which handles building the parameters and making the $http.post call to the API. ...

Deploy Node.js on a Debian server hosted on Google Compute Engine

Currently, I am operating a Debian server on Google Compute Engine using a host called example.com. My goal is to run a node.js app within a specific directory on this server, for instance, example.com/mynodeapp. Fortunately, the necessary components such ...

The rendered typeface may vary from the specified font family

I've encountered an issue with a font on my website. I'm using DIN Regular True Type Font and declaring it as follows: @font-face { font-family: 'DINRegular'; src: url('../fonts/DINBek-Regular.ttf') format('truetype ...

Is there a way to prevent an inline SVG from appearing at a random height without specifying its height or the height of its parent element?

Displayed here is a simplified Bootstrap 3 layout. The middle column in the row features an inline SVG that transitions from a blue box to a green box. I've opted for styling SVG with browser CSS because I find it interesting! Additionally, this appr ...

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

What is the method for handling a get request in Spring3 MVC?

Within the client side, the following JavaScript code is used: <script src="api/api.js?v=1.x&key=abjas23456asg" type="text/javascript"></script> When the browser encounters this line, it will send a GET request to the server in order to r ...

Handlebars: The property "from" cannot be accessed because it is not an "own property" of its parent and permission has been denied

My backend is built on Node.js and I am using server-side rendering with handlebars. I have a `doc` array of objects in handlebars that contains keys "content" and "from". However, when I try to loop through this array using `#each`, I encounter the error ...

Enhance Your jQuery Skills: Dynamically Apply Classes Based on URL Like a Pro!

Here is an example of HTML code for a progress meter: <div class="col-md-3" style="margin-left: -20px;"> <div class="progress-pos active" id="progess-1"> <div class="progress-pos-inner"> Login </div> </di ...

The server appears to be active, but there is a lack of content rendering when using React, Node

When I attempt to run the code in app.jsx, nothing displays even though the index.html is functioning properly. Code from Server.js: var express = require('express'); server.js page var app = express(); app.use(express.static('public' ...

File extension being lost when dropped in AJAX request

I am currently working on a script that uses AJAX to delete an image. PHP foreach ( $in_folder as $img => $v ) { echo ' <span class="imageHolder"> <a onclick="DeleteImage('.$img.'); return false;" href="j ...

Can you explain the inner workings of the provided code in a step-by-step manner?

I stumbled upon this code snippet that checks if the number of occurrences of an element in an array is greater than a specified value, and if so, it will remove the number: function deleteNth(arr,x) { var cache = {}; return arr.filter(function(n) { ...

Learn how to effortlessly download a file from Amazon S3 using Angular and ng-click technology

When attempting to download a file from my Amazon S3 bucket using Angular's ng-click, I am receiving a blank file instead of the expected content. HTML <div class="details-field"> RC Book <font class="digit" >({{rcCount}})</font> ...

What are some of the top languages, libraries, and modules used to create a web application for constructing templates?

Our company specializes in creating websites for membership-based associations. Currently, we utilize custom DLL's created with CodeGear Delphi to connect with a SQL Server database and implement a unique HTML template language. Essentially, our templ ...