remove CSS attribute from the JavaScript DOM properties

Can someone help me figure out what's wrong with my code? I need to remove all "link" tags with the attribute "rel = "stylesheet"

Here is the HTML code I am working with:

<html>
<head>
<title>teset</title>
<meta charset="utf-8" />
<meta name="description" content="test." />
<meta name="author" content="Me" />
<link rel="author" href="www.mysite.uk" />
<link rel="stylesheet" type="text/css" href="www.mysite.uk/css/style.css  />
<link rel="stylesheet" type="text/css" href="www.mysite.uk/css/style2.css />
</head>
<script src = "deleteCSS.js"></script>
<body onload="noCSS()">
<p> test !!</p>
</body>
</html>

Below is my JavaScript code (deleteCSS.js):

function noCSS(){ 
//I save tag "link"
var CSSlink = document.getElementsByTagName("link"); 
var CSSatt = CSSlink.getAttribute("rel");

for (var i=0; i < CSSlink.length; i++){  
if (CSSatt[i] == "stylesheet"){
CSSlink[i].remove(); }
}
}

Answer №2

const removeCSS = () => {
    const links = document.getElementsByTagName("link");

    for (let i = links.length - 1; i >= 0; i--) {
        if (links[i].rel === "stylesheet") {
            links[i].parentNode.removeChild(links[i]);
        }
    }
}
  1. Ensure to check the rel attribute of each <link> within the loop;
  2. Consider removing them in reverse order - removing one shifts the rest down in the array;
  3. Alternatively, use while (links.length) and always remove the first item at index 0.

Answer №3

If you're looking for a purely JavaScript solution:

(function() {
  var cssLinks = document.getElementsByTagName('link');
  for(var i=0; i<cssLinks.length; i++) {
    if(cssLinks[i].getAttribute('rel') === 'stylesheet') {
      cssLinks[i].remove();
    }
  }
})();

Save this code in a file called no-css.js and include it at the end of your HTML document.

The reason your code isn't working is because getElementsByTagName returns a NodeList, so calling getAttribute('rel') on it will result in a

TypeError: Object #<NodeList> has no method 'getAttribute'
. You need to iterate through each link node and remove any with the rel attribute set to stylesheet.

Hopefully this explanation clears things up for you!

Answer №4

Presented below is yet another example of JavaScript in action:

    function disableCSS(){ 

        var styleSheets = document.getElementsByTagName("link"); 

        for (i=0; i < styleSheets.length; i++ )
        { 
            if (styleSheets[i].getAttribute("rel") === "stylesheet")
            {
                styleSheets[i--].remove();
            }
        }
    }

Remember to include the closing quotation marks at the end of the href attributes, such as

href="www.mysite.uk/css/style.css"

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

Items added to a form using jQuery will not be submitted when the form is posted

Issues with posting data from dynamically appended options in a form select using jQuery have been noticed. When an appended option is selected and the form is submitted, the value does not get posted (in this case, in an email template). Adding another no ...

Unable to access placeholder information from the controller

I am new to implementing the mean stack. I attempted to view data from the controller, but encountered an error message in the web browser's console. Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.3/$controller/ctrlreg?p0=AppCtrl Stack ...

Exploring the world of Node.js, JSON, SQL, and database tables

Hello everyone, I have been working on a project using Node.js and Express framework. My current goal is to create a client-side page that allows users to input form data into a MySQL database. I have managed to successfully insert and retrieve data from ...

Achieve a full page layout with content and attach the footer to the bottom using flexbox in Tailwindcss and Nextjs

How can I use flex-grow to make the body section fill the screen and keep the nav fixed at the bottom? I'm having trouble figuring out which elements to apply these properties to. Can anyone provide guidance on which element should have these styles? ...

Conceal Element in React if it is the Final Item

Is there a way to hide the TimelineConnector if it is on the last item? I am looking for some guidance on how to achieve this. Please take a look at my codesandbox below: CLICK HERE {timelines.lastIndexOf(index) !== 1 ? <TimelineConnector /> : &quo ...

Removing an object from the scene using three.js

Is there a way to remove an object from a three.js scene? I am trying to delete a cube when a specific key is pressed, but so far I can only clear the entire scene instead of removing just one cube. ...

Having difficulty sending a value with %45 to a REST API

Currently, I'm encountering an issue within my ASP.NET MVC 5 application. The problem arises when I send the following JSON data to a third-party API, which includes a password field: "{\"operation\":{\"Details\":{\"RESOURCE ...

Coloring the Text on Buttons

After nearly 24 hours of practicing, I still can't seem to wrap my head around it. Can someone assist me in changing the button text color to white, while keeping everything else the same? //NAVIGATION //======================== .nav ul display: ...

Tips for preventing text from changing its padding within a div when reducing the width and height dimensions

I am facing an issue with a div inside another div. The child div contains text, and when I apply animation to decrease the width and height, the text inside gets reset according to the new size. While I understand why this happens, I want to find a way to ...

Creating a zigzag pattern with a linear gradient in CSS

When attempting to create a background color for my body element using linear gradient, I noticed that it resulted in a zigzag effect I experimented with the following code: Body{ background: linear-gradient(45deg, Blue 50%, red 50%) } The outcome wa ...

Can you explain the distinction between using a period in a class selector and not using one?

Could someone please clarify the meaning of the code snippet below? <div class="cls1 cls2">abcd <div class="cls2"> adfffff </div> </div> .cls1 { background-color: yellow; } /*sample1 .cls1.cls2 { color: red; } */ /* ...

Chrome fails to load webfont upon page initialization

Encountering a problem with loading a WebFont specifically on Chrome version "48.0.2564.82 m (64-bit)". The issue arises from the webfont not being applied upon page load or navigation, unless I manually refresh the page. Below is the snippet of code fro ...

Which is the superior choice: WebSocket-Node or ws? Additionally, is there a universally accepted interface for nodejs websockets available?

I am considering switching from socket.io to regular websockets in order to utilize binary data transfers and eliminate the need for base64 encoding. There are two primary websocket libraries for nodejs available on GitHub: Worlize/WebSocket-Node einaro ...

Arranging asynchronous functions using async/await in Node.js/JavaScript

When it comes to organizing my code in js/nodejs, I frequently rely on this pattern. (async function(){ let resultOne = await functionOne(); let resultTwo = await functionTwo(); return { resultOne: resultOne, resultTwo: resul ...

Having issues with the Bootstrap tabs code provided in the documentation not functioning correctly

Exploring the world of Bootstrap 5 tabs led me to copy and paste code from the official documentation (https://getbootstrap.com/docs/4.1/components/navs/#javascript-behavior), but unfortunately, it's not functioning as expected: clicking on a tab does ...

footer extending beyond the previous div's boundaries

Struggling with frontend development and creating a layout in html, css3, and bootstrap 4? I've managed to incorporate a subtle animation in the background (https://codepen.io/mohaiman/pen/MQqMyo) but now facing issues with overlap when adding a foote ...

Pressing the submit button will trigger the execution of a .php script, which will then generate a popup on the screen and refresh a specific part of

I have a select form and submit button on my page, which are dynamically generated based on entries in the database. Here is the HTML output: <div id="structures"> <h1>Build</h1> <form name="buildForm" id="buildForm" method="POST" ons ...

Numerous routers available for enhancing functionality in an Ember application

Can an Ember app have multiple router.js files? By default, one router.js file will look like this: import Ember from 'ember'; import config from '../../config/environment'; var Router = Ember.Router.extend({ location: config.locat ...

The CSS styling of Vuetify TreeView does not support text wrapping

I'm having trouble getting the long text in this CodePen snippet to break and wrap properly. It extends off screen, rendering the append button unclickable. I've experimented with various CSS rules but haven't found a solution yet. Check ou ...

Using SailsJS to populate attributes transmitted through socket.io's publishUpdate event

Utilizing the built-in socket capabilities of SailsJS has proved to be quite effective for me so far. However, I've encountered a challenge that I haven't been able to find any information on. In my model, I have set it up to populate certain at ...