How to Determine if ::before is applied to an element?

I have this simple html code. I need to be able to determine if the ::before is being applied to .icon-player-flash

    <div id="TestSwitch">

        <i class="icon-player-html5"></i>

        <i class="icon-player-none"></i>

        <i class="icon-player-flash"></i>

    </div>

enter image description here

I thought this would work but it’s always returning 0 for the length.

var flashplayer = $(".icon-player-flash:before");
console.log("count: " + flashplayer.length);

What am I missing?

1 Answer

Use getComputedStyle and check the value of content. If it’s none then the pseudo element isn’t defined:

var elem = document.querySelector(".box");
var c = window.getComputedStyle(elem,"before").getPropertyValue("content");
console.log(c);

var elem = document.querySelector(".alt");
var c = window.getComputedStyle(elem,"before").getPropertyValue("content");
console.log(c);
.box:before {
  content:"I am defined"
}
<div class="box"></div>

<div class="alt"></div>

This property is used with the :before and :after pseudo-elements to generate content in a document. Values have the following meanings:

none

The pseudo-element is not generated. ref

If you want to count simply consider a filter:

const elems = document.querySelectorAll('div');
const divs = [...elems].filter(e => {
   var c = window.getComputedStyle(e,"before").getPropertyValue("content");
  return c != "none"
});

console.log(divs.length)
.box:before {
  content:"I am defined"
}
<div class="box"></div>
<div class="box alt"></div>

<div class="alt"></div>
<div ></div>

Archive from: https://stackoverflow.com/questions/59040687/count-psuedo-elements-before-after-on-page-with-vanillajs

Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *