Search code examples
selectclickelementgetelementsbyclassname

getElementsByClassName('class') for ONLY the element that is clicked on


I have a series of divs with classes. I want to select the text within the div that is clicked on by the user.

In the example code below, if user clicks on the first div, the text consoled out should be: "Sample text ONE"

If the user clicks on the 2nd div, it should be "Sample text TWO"

I can accomplish what I want with divs that have Id's and getElementById('id').innerHTML

but I am forced to accomplish it with classes, which does not work.

Digging further: I am understanding that getElementsByClassName returns an array like object, and document.getElementsByClassName(".sample_div")[0].innerHTML will kind of work, but it only returns the first element. Perhaps there is a way to replace the 0 with the index of the div that is clicked on?

Any way to do this with classes will be great. Thank you.

<!DOCTYPE html> <html>  

<div class='sample_div'>Sample text ONE</div>
<div class='sample_div'>Sample text TWO</div>

</html>

<script type="text/javascript">    

const divs = document.querySelectorAll('.sample_div');

divs.forEach(divSelect => divSelect.addEventListener('click', notice));

function notice() {
  let text = document.getElementsByClassName('.sample_div').innerHTML;
  console.log(text);
}

Solution

  • this will contain the clicked element

    With jquery, you can create an event listener that listens to all .sample_div and reference it with this variable.

    $(".sample_div").click(function(){
      console.log(this.innerHTML)
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class='sample_div'>Sample text ONE</div>
    <div class='sample_div'>Sample text TWO</div>


    Without JQuery it should be like this:

    //Get all the elements with the class "sample_div"
    var sampleDivs = document.getElementsByClassName("sample_div")
    
    //Iterate over the sampleDivs node array
    for(var x=0, sampleDivsLength = sampleDivs.length; x<sampleDivsLength;x++){
      //Add an event listener for each DOM element
      sampleDivs[x].addEventListener("click",function(){
        console.log(this.innerHTML)
      })
    }
    <div class='sample_div'>Sample text ONE</div>
        <div class='sample_div'>Sample text TWO</div>