[removed] find strings in dom and emphasize it

后端 未结 3 1019
野趣味
野趣味 2020-12-15 12:49

i want a function that finds some strings i\'ve got in an array in the DOM and emphasize it.

eg.

keywords[0] = \'linux\';
keywords[1] = \'suse pro\';         


        
3条回答
  •  无人及你
    2020-12-15 13:34

    I had to do this a couple of months ago. Originally someone used string manipulation of innerHTML as suggested by others here but that road leads to madness. The troublesome corner cases are: What if the keyword being marked up is an element's class name or id. We also don't want to mangle any embedded javascript and accidentally cause invalid markup. Also need to handle embedded css styles. In the end you end up writing a text parser for HTML4.0 + ECMAscript + css which, even in the limited case, is a lot of work - it's writing your own web browser - IN JAVASCRIPT!

    But we already have a HTML+JS+CSS parser in the web browser that generates a nice DOM tree for us. So I decided to use that. This is what I came up with in the end:

    keywords = ['hello world','goodbye cruel world'];
    function replaceKeywords (domNode) {
        if (domNode.nodeType === Node.ELEMENT_NODE) { // We only want to scan html elements
            var children = domNode.childNodes;
            for (var i=0;i

    As long as you're careful about filtering out things you don't want to process (for example, empty text nodes that contain only whitespace - there are lots of them, trust me) this is very fast.

    Additional filtering not implemented for algorithmic clarity - left as an exercise to the reader.

提交回复
热议问题