skip to Main Content

This is how certain external css files are placed between two meta tags.

<meta id="front-template-css-anchor-start" name="front-template-css-anchor-start" content="This is where front template css will be added"/>
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/bootstrap.min.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/LineIcons.2.0.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/animate.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/tiny-slider.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/glightbox.min.css" />
    <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/main.css" />
<meta id="front-template-css-anchor-end" name="front-template-css-anchor-end" content="This is where front template css will be added"/>

In my js code, I tried to get the two meta tags like this:-

var frontTemplateCssAnchorStart       = document.querySelector('#front-template-css-anchor-start');
var frontTemplateCssAnchorEnd         = document.querySelector('#front-template-css-anchor-end');

This code,

frontTemplateCssAnchorEnd.previousElementSibling.remove();

removes <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/main.css" /> from the DOM. But I want to iterate from frontTemplateCssAnchorStart to frontTemplateCssAnchorEnd and delete/remove all <link> tags. But I am stuck and don’t know how to proceed from here.

How can I solve this?

2

Answers


  1. You can iterate through the nextElementSiblings until the end element is reached.

    for (let curr = frontTemplateCssAnchorStart.nextElementSibling, next; curr != frontTemplateCssAnchorEnd; curr = next) {
        next = curr.nextElementSibling;
        if (curr.matches('link')) curr.remove();
    }
    
    Login or Signup to reply.
  2. Something like:

    var frontTemplateCssAnchorStart = document.querySelector('#front-template-css-anchor-start');
    var frontTemplateCssAnchorEnd = document.querySelector('#front-template-css-anchor-end');
    
    var currentElement = frontTemplateCssAnchorStart.nextElementSibling;
    
    while (currentElement && currentElement !== frontTemplateCssAnchorEnd) {
      if (currentElement.tagName.toLowerCase() === 'link') {
        let nextElement = currentElement.nextElementSibling;
        currentElement.remove();
        currentElement = nextElement;
      } else {
        currentElement = currentElement.nextElementSibling;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search