开发者

Show the focused div only bookmarklet

开发者 https://www.devze.com 2022-12-24 23:43 出处:网络
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 selecte开发者_运维百科d

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 selecte开发者_运维百科d

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);


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


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.

0

精彩评论

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

关注公众号