Jquery, targetInnerHTML with CSS classes

Hey everyone. I am trying another go at a JS calculator but I’ve encountered a small problem

$(document).ready(function() {    $('button').on('click', function(e) {        let btn = e.target.innerHTML;        
  if (btn === $('.operators')) 
  { console.log('operator') } else {console.log('number');
                                                               }});});

I am trying to get btn to console.log operator and numbers separately, however it’s only giving me “number” no matter how I try to get the btn element to target it. I’m convinced i am just slightly off.
Please lend your expertise to me, thank you.

Hi,
what I understand from the code is that you have buttons and to each of them you are giving a click event listener.
In case the event is triggered, for a given button you are getting the html text inside it and compare it to an object returned by the jQuery selector. This will always be evaluated as false because the object returned will never be identical to the string inside the button.
If you want to see if a button had a class “operators”, you can do so like this:

$("button").click(function(){
  if($(this).hasClass("operators")){
    console.log("operator");
  } else {
    console.log("number");
  }
});

1 Like

Yes, that’s exactly what I wanted. Thank you!

I’m sorry I spoke too soon. I am still getting the same problem.
My code is

$(document).ready(function() {
  $('button').on('click', function(e) {
    let selection = (e.target.innerHTML);
    console.log(selection); 
                                     });
   $("button").click(function(){
  if($(this).hasClass("operators")){
    console.log("operator");
  } else {
    console.log("number");
  }
});

Still no matter what I click I get “number”

I have a temporary fix. I changed my operators to be <a> elements instead of buttons, then just did this.
It’s a band-aid over the problem, so I am still curious as to make this better.

 $('button').on('click', function(e) {
  let btn = e.target.innerHTML; 
  console.log(btn)
  console.log("number")});
  $('a').on('click', function(e) {
    let btn2 = e.target.innerHTML;
    console.log(btn2)
    console.log("operator")
  });    

https://codepen.io/Dylanbozarth/pen/jOOrNVQ?editors=1010
here is a link the full file. Tried with your provided code and I’m still getting the same error.

Being able to see the full code is always better than just a snippet.

You should only have one class attribute per element. You can put all of the class names (separated by spaces) as the value of the attribute. Currently, only the first class is being recognized if there are multiple ones (as you currently have).

1 Like