开发者

Is it possible to return the "highlighted" (like Firebug) css selector or dom id with jquery?

开发者 https://www.devze.com 2022-12-30 06:11 出处:网络
When you click the \"Click an element on the page to inspect\" arrow with FireBug, it puts a Blue Border around the target element, and also returns the DOM Id.

When you click the "Click an element on the page to inspect" arrow with FireBug, it puts a Blue Border around the target element, and also returns the DOM Id.

I am building an app开发者_StackOverflowlication and that feature would be awesome to add. Be able to hover over elements and highlight the target, upon clicking return the DOM Id or CSS selector to the application.

Is there a jquery plugin that does this magic? Some other smart way?

Thanks!,

Jonathan


$("*").mouseenter(function() {
  $(".highlighted").addClass("unhighlighted").removeClass("highlighted");
  $(this).addClass("highlighted");
});

$("*").mouseleave(function() {
  $(this).removeClass("highlighted").parents(".unhighlighted").first().addClass("highlighted");
});

JSFiddle


Easily done. What you're interested in is the target:

$(document).ready(function() {
    $(document).click(function(e) {
        alert(e.target);
        $(".highlight").removeClass("highlight");
        $(e.target).addClass("highlight");
        var id = e.target.id; // or $(e.target).attr('id');
    });
});​

Try it here: http://jsfiddle.net/3Yw4x/1/


I used what tster provided, and to get the cssPath, i wrote the following $.fn.cssPath function which returns me the css selector to reference this element in the future. So far its working great.

          $.fn.cssPath = function() {
            var currentObject = $(this).get(0);        
            cssResult = "";
             while (currentObject.parentNode) {
              if(currentObject.id) {
                cssResult = currentObject.nodeName + '#' + currentObject.id + " " + cssResult;
                break;
              } else if(currentObject.className) {
                cssResult = currentObject.nodeName + '.' + currentObject.className + " " + cssResult;            
              } else {
                cssResult = currentObject.nodeName + " " + cssResult;            
              }
              currentObject = currentObject.parentNode;
            }
            return cssResult.toLowerCase();
          }

   $("*").mouseenter(function() {
      $(".highlight").removeClass("highlight");
      $(this).addClass("highlight");        
   });

  $("*").bind('click',function(event){
    var value = $(this).cssPath();
    $('#web_page_filter',top.document).val(value);
    return false;
  });


There are some "favlets" (scripts that you add to favorites) that do the similar thing. Here's one: http://slayeroffice.com/?c=/content/tools/modi.html since favlet is just a plain old javascript you can use it's code in your page. Click on "Mouseover DOM Inspector" link to see the effect.

0

精彩评论

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