简体   繁体   English

Javascript使用CSS属性查找元素

[英]Javascript Find Elements Using CSS Property

I am writing a Greasemonkey script and at some point in the script, I want to change the background colour of every element on the page that currently has one. 我正在编写一个Greasemonkey脚本,并且在脚本中的某个位置,我想更改当前具有一个元素的页面上每个元素的背景颜色。 I know I can get elements from their ID, and change their CSS, like so: 我知道我可以从其ID中获取元素,并更改其CSS,如下所示:

document.getElementById("char").style.backgroundColor = "#FFFFFF";

But is it possible to do this the other way around, which would be much faster than looping through every element on the page to check if it has a background colour and change it? 但是是否可以用另一种方法做到这一点呢?这比遍历页面上的每个元素来检查它是否具有背景色并进行更改要快得多?

// use a new background colour instead
document.getElementByCSS("background-color").style.backgroundColor = "#FFFFFF";

I'd like to avoid JQuery. 我想避免使用JQuery。

As per what Musa said above "With inline css you could do document.querySelectorAll('[style*="background-color"]') but I cant see any way for computed styles." 按照Musa上面所说的“使用内联CSS,您可以执行document.querySelectorAll('[style * =“ background-color”]'),但我看不到任何用于计算样式的方法。” my case involves inline CSS and so it's all good. 我的案例涉及内联CSS,所以一切都很好。

I wouldn't recommend it but you could use this function 我不推荐使用,但您可以使用此功能

function findByCss( prop, val ) {
        var 
        retArr = [],
        allElms = document.getElementsByTagName('*'),
        computed,
        i = 0;
        for ( ; i < allElms.length; i++ ) {
            computed = window.getComputedStyle( allElms[i], null ).getPropertyValue(prop);
            if ( computed.indexOf( val ) >= 0 ) {
                retArr.push( allElms[ i ] );
            }
        }

        return retArr;

    }

It returns an array of elements which computed styles CONTAIN the value of the style property you are looking for, you can change it to be an less tolerant conditional if you would like. 它返回一个计算样式的元素数组,该样式包含要查找的style属性的值,您可以根据需要将其更改为容忍度较低的条件。 On another note all hex color codes get computed as RBG, so you would have to find the RGB value for the hex code before using this function in your case. 另外请注意,所有十六进制颜色代码均以RBG进行计算,因此在使用这种功能之前,必须先找到十六进制代码的RGB值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM