[RUBY] About getElementsByClassName and addEventListener

I may make the same mistake again because I don't understand much now. Keep a record so that you can look back and check it at that time.

Background

While implementing the delete function with rails, I want to display a confirmation dialog before deleting, so I write it in the Javascript file.

html.erb


 <%= link_to 'Delete', hoge_path(hoge.id), class: 'delete-btn', method: :delete %>

javascript



function check() {
  const btn = document.getElementsByClassName('delete-btn');
    btn.addEventListener('click', () => {
    window.confirm('Perform a delete')
  })
 };

I try to click the delete button, but the dialog does not appear and the deletion is executed. It reloads and tries again, but it is deleted without anything.

Conclusion

Changed the description of the html file as follows

html.erb


 <%= link_to 'Delete', hoge_path(hoge.id), class: 'delete-btn', method: :delete, data: { confirm: 'Deleteを実行します。よろしければOKをクリックしてください。' } %>

After checking, it is said that a dialog will be displayed if you write ``` data: {confirm:" words to be displayed "}` in link_to``. Solved for displaying dialog.

Main subject

So what if you want to use addEventListener in a JavaScript file?

  1. If there is only one element to get, give an id and get it with `` `getElementById```.
  2. Get the element with `querySelectorAll``` → Use the forEach`` function for the obtained element

The foreach function is a method of the NodeList object, and NodeList is the return value of querySelectorAll. Therefore, use querySelectorAll instead of `` getElementsByClassName``` to get the elements. <br> By the way, the return value of ``` getElementsByClassName``` is `HTMLCollection```.

Impressions

I'm still not very familiar with it, and since I'm writing by connecting what I've researched for the time being, there are many parts that I can't understand. I felt that I had to study so that I could deepen my understanding.

Reference article

Recommended Posts

About getElementsByClassName and addEventListener
About Serializable and serialVersionUID
About Java Packages and imports
About Ruby and object model
About Ruby classes and instances
About instance variables and attr_ *
About =
About object-oriented inheritance and about yield Ruby
About Java primitive types and reference types
This and that about Base64 (Java)
About Docker, disguise server and container
About the difference between irb and pry