1

I would like to use chrome API (JavaScript) to create simple DOM inspector (you know the DOM inspector from Firefox developers tools where you can click over DOM element and it will display some information about the element). I am not using directly Chrome browser, but chrome API which is used by Firefox. I know how to bind event with element using addEventListener like this:

target.addEventListener(type, listener[, options]);
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture, wantsUntrusted]); // Gecko 

But the target in the code above is some specified element. My question is how to implement the idea when I don't know which element will be clicked. I mean, should I bind the listener to all DOM elements? Hopefully there is some better, easier and universal solution for this. I add the google-chrome API tag because I think the implementation in Firefox webextensions should be similar like in Chrome.

John Boe
  • 3,016
  • 10
  • 32
  • 56
  • Bind your event listener to the document – Dave Jul 19 '16 at 16:09
  • 1
    Possible duplicate of [What is DOM Event delegation?](http://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) – Dave Jul 19 '16 at 16:11

2 Answers2

2

You can just bind one global click listener:

document.addEventListener('click', function(e) {
  var element = e.target;
  // do anything you want with the element clicked
  console.log(element);
});
floribon
  • 18,567
  • 4
  • 50
  • 66
1

Just capture all the clicks on the document, this way uses jquery, but it can also be done in pure js. then use event.target see code below. I also included ie6-7 support.

$(document).click(function(e) {
  // Support IE6-8
  var target = e.target || e.srcElement;
  console.log(target)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>blah blah blah div 1</div>
<span>blah blah blah span 1</span>
<p>blah blah blah p 1</p>

MDN reference

Ben Davison
  • 610
  • 6
  • 13