【问题标题】:Selecting elements with a certain background colour without jQuery在没有jQuery的情况下选择具有特定背景颜色的元素
【发布时间】:2021-05-04 02:33:54
【问题描述】:

我想在其 CSS 包含特定背景颜色的 div 中选择一堆跨度。我如何做到这一点?

(这与this question 的问题相同,但我正在寻找非jQuery 解决方案。)

【问题讨论】:

    标签: javascript css


    【解决方案1】:
      var new_elemt =[];
      (function() {
    
      // Get all elements that have a style attribute
      var elms = document.querySelectorAll("*[style]");
    
      // Loop through them
      Array.prototype.forEach.call(elms, function(elm) {
        // Get the color value
        var clr = elm.style.backgroundColor || "";
    
       if(clr!=""){
       new_elemt.push(elm);
       }
    
       
      });
    })();
    

    【讨论】:

      【解决方案2】:

      // Get all spans
      let spans = document.querySelectorAll('div#someDiv span'); 
      
      // Convert spans nodeslist to array
      spans = Array.from( spans ); 
      
      // Filter spans array
      // Get CSS properties object of selected element - [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle)
      let arr = spans.filter( span => String( document.defaultView.getComputedStyle( span, null ).backgroundColor ) == 'rgb(0, 0, 0)' );
      
      // Change background color of matched span elements
      arr.forEach( span => {
          span.style.backgroundColor = 'green';
      });
      .one, .two {
        background-color: black;
      }
      
      .three {
        background-color: red;
      }
      <div id="someDiv">
          <span class="one">test one</span>
          <span class="two">test two</span>
          <span class="three">test three</span>
      </div>

      【讨论】:

        猜你喜欢
        • 2013-05-27
        • 1970-01-01
        • 2018-01-15
        • 1970-01-01
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多