-1

I am trying to loop through an element with class name and find the input value inside it:

 document.querySelectorAll('.qty').forEach(element=>{
        console.log($(this).find('input').val())
    })

This returns undefined

However, if I change the code above to:

 document.querySelectorAll('.qty').forEach(element=>{
        console.log($('.qty').find('input').val())
    })

Isn't this supposed to refrence the class name with quantity. Why does this not work?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
jedu
  • 1,211
  • 2
  • 25
  • 57

3 Answers3

2

Because you're using an arrow function which does not contain its own this binding. Use an ordinary ES5 function:

document.querySelectorAll(".qty").forEach(function(element) {
  console.log($(this).find("input").val());
});

To make your code more concise, you could use jQuery's inbuilt functions, and discard the unused element parameter.

$(".qty").each(function() {
  console.log($(this).find("input").val());
});

Or forget about this and use the parameter, which would allow you to use an arrow function:

$(".qty").each((_, e) => console.log(e.find("input").val()));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 1
    Please close duplicates – adiga Aug 03 '19 at 03:51
  • 1
    My bad @adiga, I didn't know that a duplicate of this question existed, and I don't have a list of duplicate questions because I'm not too heavy on the dupehammer provided by a gold tag badge to require one. – Jack Bashford Aug 03 '19 at 03:54
1

$(this) inside forEach is representing the the global window object. If you prefer to use jquery change it to $('.qty').each instead of using querySelectorAll

$('.qty').each((i, v) => {
  console.log($(v).find('input').val())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='qty'>
  <input type="text" value="1"></div>

<div class='qty'>
  <input type="text" value="1"></div>

<div class='qty'>
  <input type="text" value="1"></div>

<div class='qty'>
  <input type="text" value="1"></div>
brk
  • 48,835
  • 10
  • 56
  • 78
0

This in javascript behaves a little differently. the value of this is determined by how a function is called (runtime binding).

For further explanation please refer to this documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

athxp
  • 71
  • 9