开发者

Add text after element that contains string

开发者 https://www.devze.com 2023-01-07 05:38 出处:网络
I want to write an extension for Google chrome that detects snippets of source code on web pages and automatically copies them to the clipboard.

I want to write an extension for Google chrome that detects snippets of source code on web pages and automatically copies them to the clipboard.

I'm new to javascript and jquery, so for the first step, I wanted to try a very simple case.

Using this site as an example: http://www.swharden.com/blog/2010-03-05-realtime-fft-graph-of-audio-wav-file-or-microphone-input-with-python-scipy-and-wckgraph/

I want to find the element that contains the str开发者_StackOverflowing "import " and add the text "Here is some code" after the element. Could someone give me a clue?

My first attempt was $('*:contains("import ")').after("Here's some code");, but that inserted after every element, including the parents, when I only want to insert after the lowest level child.

Edit: I want the code to work on any site. So I want to find any element that contains the "import ". Solutions specific to the example site aren't what I'm looking for.


Go through each text node on the page and search for the query - "import". If it matches, then append the string "Here's some code" after it's parent().

$("body *").contents().filter(function() {
    if(this.nodeType != Node.TEXT_NODE) {
        return;
    }
    if(this.nodeValue.indexOf('import') == -1) {
        return;
    }
    $(this).parent().after("Here's some code");
});

Using your given example, this will add "Here's some code" after each line of code. To find out where exactly the code begins, you will have to apply some heuristics.


works for me on your example site

$(".prettyprint span:contains('import')").after(" Here's some code");

make sure this code runs as a callback after the syntax prettifier is done

0

精彩评论

暂无评论...
验证码 换一张
取 消