s.shpiz
s.shpiz

Reputation: 145

Grabbing HTML from rectangle

What i would like to do is to allow the user to draw a rectangle on top of a website, and grabbing all the html he sees in that rectangle.

I know this can't be done perfectly but I was wondering how well it could be done.

i was thinking of doing something like this

function getTagsInArea(p1, p2){
    var ret = {}
    for(x=p1.x;x<p2.x;x+=10){
        for(y=p1.y;y<p2.y;y+=10){
            var el = document.elementFromPoint(x,y);
            if(typeof ret[el] =='undefined'){
                ret[el]=el;
            }
            else{console.log('not appending '+el);}
        } 
    } 
    return ret;
}

This gives me more or less the tags in that area. I wonder if there is a generic way to build trees from these tags and output html.

I am looking for something like a DocumentFragment. Such as selectionContents from this snippet:

var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();

Is there an obvious way to do this? One of the problems so far is that some of the tags i get using the above func are 'body' and 'div id="page"' stuff, which contain what i am looking for. Any solution would need to figure out how to take only those parts of the surrounding tags taht are needed.

For instance, if i have a long paragraph and recntagled half of it, i want only the text in my selection to be returned.

Hope this question makes sense.

Upvotes: 3

Views: 1622

Answers (2)

Lucas
Lucas

Reputation: 10646

javascript and jQuery aren't my strong points but I thought I would try to write a small example of what I think you want.

Unfortunately I don't have time to finish so currently the selection box can only drag left and down but if it is what you'e after then I'm sure you will be able to alter it.

Currently I'm just building a text list of selected tags which I'm printing out after mouse up, but it loops through in order so it shouldn't be much problem to store all of these tags in an array if you wanted.

Of course you could also use $(this).html() in the each loop to get the contents of each selected tag too.

Sorry if I mis-understood your question, but was this the kind of thing you were after?

jsfiddle: http://jsfiddle.net/cgKzv/ (Written and tested in Chrome)

Upvotes: 3

mitch
mitch

Reputation: 1831

Provided you know the area of your triangle, you can possibly surround all characters of text with span tags like this and THEN do a check if those span tags fall within your rectangle. To make it easier, I would assign classes to these span tags. Then, concatenate the text using $.each() to loop the span tags,check if they fall within the rectangle, and , if they do, concatenate to a string variable. Also, if you use document.elementFromPoint(), it will only return the element that is at that position with the highest z-index (in case your had some elements layered).

Upvotes: 1

Related Questions