-1

Whats the equivalent of the below jquery code using javascript?

$("#id").on("click",function(event){alert(event.target.id);});

I know i can use the below code

document.addEventListener('click', function(e) { alert(e.target.id)  }, false);

But i want to constrain it to a particular id and not the whole document.

  • 3
    `document.getElementById('id').addEventListener('click', function(e) { alert(e.target.id) }, false)` – Satpal Jul 28 '15 at 09:29
  • possible duplicate of [jQuery.click() vs onClick](http://stackoverflow.com/questions/12627443/jquery-click-vs-onclick) – Hacketo Jul 28 '15 at 09:30
  • [mdn](https://developer.mozilla.org/en/docs/Web/API/EventTarget/addEventListener): _The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on. The event target may be an **Element** in a document, the **Document** itself, a **Window**, or **any other object that supports events** (such as XMLHttpRequest)._ – Grundy Jul 28 '15 at 09:30

4 Answers4

0

To attach an event handler on an element, selected by id, you can do:

document.getElementById('id').addEventListener('click', function(e) { 
   alert(e.target.id)  
}, false);

n.b. the false at the end is an optional parameter bool for capture, from MDN:

If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture.

atmd
  • 7,430
  • 2
  • 33
  • 64
0

Do this

document.getElementById('id').addEventListener('click',
function(e) 
{
    alert(e.target.id);
}, false);

The last parameter is useCapture.

Reference - W3SCHOOLS

true - the function is executed in the capturing phase.

false - the function is executed in the bubbling phase. (Default)

No need to worry as it is optional in all browsers now.

Shrinivas Shukla
  • 4,325
  • 2
  • 21
  • 33
0

Get element by id and attach event lister

document.getElementById('id').addEventListener('click', function(e) { 
  alert(e.target.id) 
}, false);

Use of boolean at the last is optional. A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.

For more Information - addEventListener

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

Try this :

var id = document.getElementById("id");

id.addEventListener("click", function(e) {
    alert("hi");
},false);
Adrian Thompson Phillips
  • 6,893
  • 6
  • 38
  • 69
Rohit Arora
  • 2,246
  • 2
  • 24
  • 40