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

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>

Leave a Comment