Reputation: 737
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>
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?
Upvotes: 5
Views: 2596
Reputation: 273086
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>
Upvotes: 5