5

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.

5
  • 1
    Look up EventTarget.addEventListener(). Commented Aug 1, 2017 at 8: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 instead of jQuery? (The language, JavaScript, is the same regardless.) Commented Aug 1, 2017 at 8:29
  • What @Phylogenesis said. And if you need to support obsolete browsers like IE8 that don't have it, this answer has a version for you with fallback. Commented Aug 1, 2017 at 8:30
  • @T.J.Crowder why duplicate? The question of "ready" was just an addition. The most important was "on" and selector. Commented Aug 1, 2017 at 8: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 and web search in future. Commented Aug 1, 2017 at 8:40

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

$(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.
  }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.