views:

63

answers:

2

I'm searching to select a text from a div, then click on a bookmarklet that remove all html parts in the body except the div where the text is selected

maybe jquery can help with something like :

javascript:var%20s=document.createElement('script');s.setAttribute('src',%20'http://jquery.com/src/jquery-latest.js');document.body.appendChild(s);s.onload=function(){/*the code*/};void(s);
+1  A: 

Assuming the text you selected appears exactly once on the page this should work. If it appears multiple times this should show the last div on the page which contains the selected text.

More readable

function sel() {
    if (window.getSelection) {
        return window.getSelection().toString();
    } else if (document.getSelection) {
        return document.getSelection();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
}
var s = document.createElement('script');
s.setAttribute('src', 'http://jquery.com/src/jquery-latest.js');
document.body.appendChild(s);
s.onload = function () {
    var x = $(":contains('" + sel() + "')").last().parents("div").eq(0);
    $("body").empty().append(x);
};
void(s);

As one-liner

javascript:function sel(){if(window.getSelection) return window.getSelection().toString();else if(document.getSelection) return document.getSelection();else if(document.selection) return document.selection.createRange().text;} var s=document.createElement('script');s.setAttribute('src','http://jquery.com/src/jquery-latest.js');document.body.appendChild(s);s.onload=function(){var x=$(":contains('"+sel()+"')").last().parents("div").eq(0);$("body").empty().append(x);};void(s);

If you also want the css stylings to be gone you must empty the <head> too

jitter
Thank you, this is exactly what I was looking for ! The sel() is even crossbrowser :-)
ideotop
A: 

If i understood u right ur looking at something like this.

html

<body>
  <div class="bookmarklet">
    bookmarklet Text
  </div>
  <div>
    <div>
     <div class="bookmarklet">
      bookmarklet Text
     </div>
     <div>Usless</div>
     <div>Usless</div>
    </div>
    <div>Usless</div>
  </div>
  <script>
    $('bookmarklet').unbind('click').bind('click',function(){
      var text = $(this).text();
      $('body').html('').append(text);
    })
  </script>
</body>

Now this will work if you have put the script tag for the jquery on the header if you don't know how to then comment below.

Val