How to select only one div of several equals with js?

2

I'm creating a posts system made with divs , however as all divs will have the same class nomenclature I need that when I click on some javascript attack only own javascript without interfering in others. Only with js, I do not use jquery!

Example, if I click open the menu of the post, I want only this menu to open without opening the other posts.

    
asked by anonymous 10.01.2017 / 02:54

2 answers

2

With jquery the click method takes all the elements with a certain class, after that you send the clicked by parameter and get with this ...

$('.ctn').click(function(e){
	alert($(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="ctn">
  div 1  
</div>
<div class="ctn">
  div 2
</div>
<div class="ctn">
  div 3 
</div>
<div class="ctn">
  div 4
</div>
    
10.01.2017 / 03:19
1

With pure JavaScript:

var elementoAtual = document.getElementsByClassName("minha-classe");

Array.prototype.slice.call(elementoAtual).forEach(function(pegaElementoAtual){
    pegaElementoAtual.addEventListener('click', function(e){
       alert(this.innerHTML);
    });
});
body{
    font-family: 'calibri light', sans-serif;  
}
div{
    padding: 5px;
}
div.minha-classe{
    text-align: justify;
    text-indent: 25pt;
}
<div class="minha-classe">
    Adult education is essential for Democracy of India. The number of grown up illiterates is great. All college and senior School students should come forward to visit villages in the summer vacation. Each one will teach one there. This will remove illiteracy and strengthen our democracy.
</div>
<div class="minha-classe">
    I happened to see a one day cricket match between Pakistan and Australia at Wankhade Stadium, Mumbai. I went for a fun. But I witnessed a horrible sight. Two thousand ticketless cricket fans gate crashed. There was a stampede. Three persons died and twenty were injured. Administration was responsible for it.
</div>
<div class="minha-classe">
    City Anti-pollution Drive demands certain steps from all the citizens of ABC city. All house-holders should pack the waste in a plastic bag and put the bag in front of their house. The bag will be replaced with an empty bag by the Municipal van every morning. They should maintain the cleanliness of the city. This will make the city pollution free.
</div>

You have not posted any code, but this can be easily crafted with the following ( with JQuery ):

$('div.minha_classe').on('click', function(){
   var elementoAtual = $(this);
   // Faça o que quiser a partir daqui
});
    
10.01.2017 / 03:18