Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .find() inside .each() not working

Currently I'm stuck in a very basic jQuery problem. I think there's something I do not understand about jquery's .each().

So this is my code:

     $('.test-list .test-item').each(() => {
        console.log($(this).find('.test-paragraph').text()); //not working always empty
     });

I'm just iterating over a bunch of items which perfectly works. But then I want to get the text of the.test-paragraph inside my element. The problem is that the find() method isn't working. Alle the html element exist.

<div class="test-list">
   <div class="test-item">
      <p class="test-paragraph">Test 1</p>
   </div>
   <div class="test-item">
      <p class="test-paragraph">Test 2</p>
   </div>
   <div class="test-item">
      <p class="test-paragraph">Test 3</p>
   </div>
</div>

Does anyone know what's the problem?

like image 719
Orlandster Avatar asked Feb 12 '17 15:02

Orlandster


People also ask

How does find work in jQuery?

jQuery find() MethodThe find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.

What is $() in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)

How to use for each in jQuery?

The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.

How to get text from input in jQuery?

To get the textbox value, you can use the jQuery val() function. For example, $('input:textbox'). val() – Get textbox value.


1 Answers

As per the MDN doc :

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. Arrow functions are always anonymous. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Inside of arrow function this won't refers to the element, so instead use the normal function.

$('.test-list .test-item').each(function() {
   console.log($(this).find('.test-paragraph').text());
});

Or you can use text() method with a callback to iterate and get text content of the element.

$('.test-list .test-item .test-paragraph').text((i, text) => console.log(text))

Or instead of this use the second argument in the arrow function and as per the docs which refer to the element.

$('.test-list .test-item').each((i, ele) => console.log($(ele).find('.test-paragraph').text()));
like image 120
Pranav C Balan Avatar answered Oct 28 '22 12:10

Pranav C Balan