Please help translate jQuery to classic JavaScript code:

$("#id1").on('click', 'input[type=radio]', function(){ alert('hello'); } 

Thank!

  • jquery .on () works quite hard, in your code it catches the click event on all existing (and added later) 'input [type = radio]' elements inside '# id1', you can find them through document.querySelectorAll('#id1" input[type=radio]') and put the handler through addEventListener to each, but this will not affect the newly added elements. - Sanya_Zol

2 answers 2

 document.getElementById("id1").addEventListener('click', function(e){ alert('hello'); }); 
  • one
    this code. different from what is in question. Here a handler is added for the element with id = "id1" while in the question - click on input [type = radio] - Grundy

We need to understand what's what:
Element #id1 , a click event is #id1 and, if the target element is input[type=radio] , performs a callback .
That is, this is the implementation of delegation, which is useful when a bunch of similar elements, plus - the dynamic addition of elements without special witches.

Let's rock:

 function on(parent, evName, css, fn){ // Ищем контейнер и вешаем слушатель на нужное событие document.querySelector(parent).addEventListener(evName, function(e){ // Целевой элемент и ближайший возможный предок (или сама цель), удовлетворяющий селектору выборки let target = e.target, input = target.closest(css); // Если элемент, подходящий под выборку, не найден или он вне контейнера - выходим! if (!input || !this.contains(input)) return; // Да, всё подходит, вызываем функцию-слушатель, передавая this и объект события fn.call(target, e); }); } on('#id1', 'click', 'input[type=radio]', function(e){ console.info(this.value); }); // Реализуем добавление блоков let id = 0; document.querySelector('#addGood').addEventListener('click', e => { let el = document.createElement('input'); el.type = 'radio'; el.value = 'Element N' + id++; document.querySelector('#id1').appendChild(el); }); document.querySelector('#addBad').addEventListener('click', e => { let el = document.createElement('input'); el.type = 'text'; el.value = 'Element N' + id++; document.querySelector('#id1').appendChild(el); }); 
 <div id='id1'> <input type='radio' value='One' /> <br /> <input type='text' value='А тут не работает!' /> <br /> <input type='radio' value='Two' /> <br /> </div> <hr /> <input type='button' id='addGood' value='Add radio block' /><br /> <input type='button' id='addBad' value='Add bad block' />