-2

I want to make a js class selector like in jquery.

$('.someClass').click(function(){
    alert($(this).value());
});

I have tried in javascript .

function myFunction(this){
    alert(this).value;
}
document.getElementsByClassName('someClass').onclick = "myFunction";

this isnt working for me and I have also refered to many other forums in stack overflow.

THIS IS NOT DUPLICATE ... IF YOU FIND IT PLEASE HELP ME WITH THE LINK

  • 1
    alert(this).value; should be alert(this.value); – daremachine Mar 07 '19 at 16:21
  • `getelementsByClassName` returns a HTMLCollection, which is not a single element, so the attempt to use `.onclick` on it, as if it is a single element, in incorrect. You would have to loop over them and apply the onclick. Also, the assignment of the `onclick` should be just `myFunction`, and not a string. Alternatively you would need to consider using the `addEventListener()` method to set it, rather than the property. And then your method has the issue of the `.value` being on the alert, and not the `this`. – Taplar Mar 07 '19 at 17:23

1 Answers1

2

Use a querySelectorAll to get all elements with that class, then use a forEach to loop through them and add an event listener to each:

Coded using jQuery:

$('.someClass').click(function(){
    console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span class="someClass">Hello, World!</span>
<span class="someClass">1, 2!</span>
<span class="someClass">3, 4!</span>

Coded with pure JS:

var all = document.querySelectorAll('.someClass');

all.forEach((e) => {
  e.addEventListener('click', () => {
    console.log(e.innerText);
  })
});
<span class="someClass">Hello, World!</span>
<span class="someClass">1, 2!</span>
<span class="someClass">3, 4!</span>
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55