Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 application 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

like image 776
Jonathan Avatar asked May 10 '10 14:05

Jonathan


3 Answers

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

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

JSFiddle

like image 153
tster Avatar answered Oct 20 '22 08:10

tster


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/

like image 42
karim79 Avatar answered Oct 20 '22 06:10

karim79


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;
  });
like image 1
Jonathan Avatar answered Oct 20 '22 08:10

Jonathan