9

I have the following case: (styling is done in SASS and unnecessary stylings are omitted.)

.header {
  ...
  &::before {
    ...
    position: absolute;
    height: 0.5rem;
    ...
  }
}

This creates a bar on top of the application's menu bar. In certain cases this bar has to be removed. I have read questions like these, but with no success. What would be the best way to remove this bar added by the ::before selector?

Community
  • 1
  • 1
Jan Swart
  • 6,761
  • 10
  • 36
  • 45

4 Answers4

11

Only CSS can remove pseudo element, so you need to have an other class that display:none; the before. First declare that class in the CSS :

.header {
  ...
  &::before {
    ...
    position: absolute;
    height: 0.5rem;
    ...
  }

  &.no-before::before{
    display:none;
  }
}

Then, when you want to remove it :

$('.header').addClass('no-before'); //Remove before
$('.header').removeClass('no-before'); //Re-add before
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
7

The usual way is to create a more specific rule that applies to the element(s) in question (or a later rule with the same specificity), and specify display: none to hide the pseudo in that case.

For example: Here, I want to have an X in front of <span class="foo">, but not if they're in .header:

span.foo::before {
  content: 'X ';
}
.header span.foo::before {
  display: none;
}
<div>
  These have the X:
  <span class="foo">span.foo 1</span>
  <span class="foo">span.foo 2</span>
  <span class="foo">span.foo 3</span>
</div>
<div class="header">
  These don't:
  <span class="foo">span.foo 4</span>
  <span class="foo">span.foo 5</span>
  <span class="foo">span.foo 6</span>
</div>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

If you are manipulating the DOM by using JavaScript, you can add a class name - for instance .remove-bar - to the element having .header in order to remove the pseudo-element (generated content):

.remove-bar {
    &::before { content: none; }
}

Also make sure that it is placed after the previous styles, or use a more specific selector if needed.

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
0

For remove special element use this method.

<button onclick="myFunction()">Remove</button>
<div id="myList">
  <div>  Coffee            </div>
  <div id="child2" > Tea   </div>
  <div> Milk               </div>
</div>

your JavaScript :

<script>
function myFunction() {
  const list = document.getElementById("myList");
  if (list.hasChildNodes()) {
    list.removeChild(list.children[0]);
  }
}
</script>

you can combine above function with this code:

const parent = document.getElementById('myList');
const children = parent.children;
let index = -1;
for (let i = 0; i < children.length; i++) {
  if (children[i].id === 'child3') {
    index = i;
    break;
  }
}
alert(index); // ️ 2
m-tech
  • 338
  • 2
  • 14