1

I have in jQuery:

$(document).ready(function() {
   $(document).on('click', "[id$='someId']", function () {
      console.log($(this).val());
   })
})

How can I write it in pure JavaScript?

$(document).ready(function()

Should I use "ready" in pure JavaScript?

$(document).on

How can I use "on"? I have to add dynamic elements, so in jQuery I must use "on".

I would like write this in accordance with ES6.

lakego
  • 29
  • 1
  • 4
  • 1
    Look up [`EventTarget.addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). – Phylogenesis Aug 01 '17 at 08:25
  • *"Pure JavaScript instead of jQuery"* ***sigh*** There's nothing impure about your JavaScript if you use jQuery or any other library. What you mean is, how can I do this with the [DOM](https://www.w3.org/DOM/DOMTR) instead of jQuery? (The **language**, JavaScript, is the same regardless.) – T.J. Crowder Aug 01 '17 at 08:29
  • What @Phylogenesis said. And if you need to support obsolete browsers like IE8 that don't have it, [this answer](http://stackoverflow.com/a/23799448/157247) has a version for you with fallback. – T.J. Crowder Aug 01 '17 at 08:30
  • @T.J.Crowder why duplicate? The question of "ready" was just an addition. The most important was "on" and selector. – lakego Aug 01 '17 at 08:37
  • *"How can I write it in pure JavaScript? `$(document).ready(function()`"* quite clearly asks what the linked question's answers answer. That's the problem with unfocussed questions. In any case, the `on` thing is ***trivially*** easy to find -- here on SO, and elsewhere, with the barest minimum of research. Please [search](/help/searching) and web search in future. – T.J. Crowder Aug 01 '17 at 08:40

2 Answers2

9

Use addEventListener instead of on:

document.addEventListener('DOMContentLoaded', function () {
  document.body.addEventListener('click', function (e) {
    if (e.target.matches("[id$='someId']")) {
      console.log(e.target.value);
    }
  });
});

The event delegation makes it a bit more complex, but it should do the trick.

PeterMader
  • 5,739
  • 1
  • 16
  • 27
1

$(document).ready(function()

// DOMContentLoaded
// @see https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
document.addEventListener('DOMContentLoaded', function (event) {
  console.log('DOM fully loaded and parsed');
});

$(document).on

document.addEventListener("click", function(event) {
  var target = event.target;
  if (target.id === 'a') {
    // do something.
  } else if (target.id === 'b') {
    // do something.
  }
});
Givebest
  • 11
  • 2