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

前端 未结 1 426
长情又很酷
长情又很酷 2020-11-29 11:40

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

    
相关标签:
1条回答
  • 2020-11-29 12:29

    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>

    0 讨论(0)
提交回复
热议问题