简体   繁体   中英

Find a custom text and change its color using JavaScript and CSS

I'm building a site and just met the limitations of WordPress and custom theme, tho I can inject custom Js or CSS easily, so my question is...

How to find in content and set its color

More about symbol https://www.htmlsymbols.xyz/unicode/U+2605

var headings = document.evaluate("//li[contains(., '★')]", document, null, XPathResult.ANY_TYPE, null );
var thisHeading = headings.iterateNext();
thisHeading.setAttribute('style', 'color: #f1c40f');

Got it! I'm leaving the tags below in case someone searches for this solution

css, unicode, color, javascript, find

You can loop through the entire dom and search for matches.

let allElements = document.getElementsByTagName("*");
    for (let Element of allElements) {
        for (let childNode of Element.childNodes) {
            if (childNode.nodeType === 3) {
                let valueUpper = childNode.nodeValue.toUpperCase()
                if (valueUpper.includes(text)) {
                    Element.style.backgroundColor='#ff0000';
                    Element.style.color='#ffffff';
                }
            }
        }
    }

I used this code: https://stackoverflow.com/a/6132212/8781059

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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