LiJung
LiJung

Reputation: 7959

Find the exact content in a website by using javascript

I'm trying to write a function that I could save and display the exact place I selected in a website.

And I've found out getSelection() object in javascript is something I am looking for (cause it save all the information). But now I'm trying to highlight the place where I've chose before by using the getSelection() object.

Could I back trace the place by using getSelection()? I think there should be some better solutions but I couldn't think of any right now.

In other words, I'm trying to save some data, for tracing back the exact place I selected.

Did anyone have any ideas? Or better solution. Thanks.

Upvotes: 0

Views: 132

Answers (1)

Craig Blagg
Craig Blagg

Reputation: 536

If you know what the parent tag is, you could loop through those, and use a regex to find where the copy is within that element.

Using something like the below, will wrap all instances of the matching phrase in a span with a yellow background.

I've put an example fiddle at: http://jsfiddle.net/TDcKX/2/

function find_phrase(phrase){
    var p_tags = document.getElementsByTagName('p');

    for (var i = 0; i < p_tags.length; i++){
        var p = p_tags[i], regex = new RegExp(phrase, 'g');
        p.innerHTML = p.innerHTML.replace(regex, '<span style="background-color:yellow;">' + phrase + '</span>');
    }
}

Upvotes: 1

Related Questions