Read id clicked and store in a var to reuse

Asked

Viewed 39 times

0

I have until now this code :

   document.getElementById('collapseOne').on('click', function(event){  
        event.preventDefault();
        collapseItem(event);
   });

but I have more than 1 Collapse (in total four only modifying the numbering at the end of id) And I’d like the code to be just that. I thought of creating a Function to read the id clicked inside the father div where the Collapse meet but unsuccessfully

function clickCollapse(){
  var el = document.getElementById('accordionExample');

  el.addEventListener('click', function(e) {
       var idCollapse = "'" + (e.target.id) + "'";
  });
}

so having to just replace this part of the code

document.getElementById('collapseOne');

by the id captured in this last example block:

document.getElementById('idCollapse');

but it didn’t work

  • Try to take the variable idCollapse without string concatenation, just e.target.id, and at the time of picking it up in Document.getElementById(idCollapse); do it without the quotes

  • If you use a class, and use the $(this) jQuery, to catch the attr id may work. Post the structure of your collapse also that helps.

1 answer

0

Oops, from what I saw, you’re going through the event to a function that did not detail what it does, perhaps misspelled.

I think a much simpler solution is to reference all these elements by a "universal" selector, also called wildcards and make a for and to declare that each of them has this click. It also has the option of custom attributes, like collapseAttr=id_1 and then you take the value of the attribute, but let’s id since it is your need.

var elementos = document.querySelectorAll('[id^=collapse]') // isso quer dizer "todos elementos que começam com  > collapse <"

function suaFuncao() {
  alert(this.id)
  // sua tratativa aewww
}

for(var i = 0; i < elementos.length; i++) {
  elementos[i].onclick = suaFuncao
}
<p id="collapse1">click 1</p>
<p id="collapse2">click 2</p>
<p id="collapse3">click 3</p>
<p id="collapse4">click 4</p> 

I hope I’ve helped!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.