Robbie Dee
Robbie Dee

Reputation: 49

How to convert jQuery to JavaScript name attribute

I'm trying to find a way to create 'on click' events for dynamically generated buttons in JS. I know that in jQuery it can be done like this:

$(document).on('click', 'name=[buttonName]', function() {}); 

I know the e.target method in JS, but I'm wanting to find a way to do it with a name attribute instead.

Thanks

Upvotes: 1

Views: 103

Answers (3)

Jeyas
Jeyas

Reputation: 9

You can use getElementByName to add click event to your button which is dynamically render

document.getElementByName("ButtonName").addEventListener("click", function(e) {
});

Upvotes: 0

Jamiec
Jamiec

Reputation: 136094

You can use querySelector in a similar way than you would in jQuery, and attach the event listener whenever a new element is added to the DOM.

document.querySelector("button[name='buttonName']").addEventListener("click", function(){
   alert("Hello, World");
});
<button name="buttonName">Click me</button>

The difference to the original jQuery code is that in that example it listens to events on the document whereas this does not.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly that line of jQuery isn't quite right as the square brackets are in the wrong place:

$(document).on('click', '[name="buttonName"]', func); 

To achieve the same in plain JS you would need to attach a click event handler to a static parent element, then check the name property of the clicked element:

document.addEventListener('click', function(e) {
  if (e.target.name == 'buttonName') {
    // do something...
  }
});

document.addEventListener('click', function(e) {
  if (e.target.name == 'buttonName') {
    alert('Hello!');
  }
});
<button>I do nothing!</button>
<button name="buttonName">I say hello!</button>

Upvotes: 1

Related Questions