Traverse a jQuery object and the differencebetween this and $(this)
I want to traverse a jq object (which is a type of object used in jQuery) and print the inner text in every selected items. However, when I used either for (let x in jq_obj)
nor for (let x of jq_obj)
, I received an error that 'x.text() is not a function'. Then I tried the foraEach()
method, browser showed that jq_obj is not iterable. Then I searched error message, I gained a clearer understanding.
Firstly, jq_obj is not an iterable object. If we want to access the inner elements, jq_obj has a each()
method which can be used to iterate over a jq_obj, and is equivalent to forEach()
which belongs to DOM object.
Secondly, while each()
method traverses a jq_obj, it will pass a DOM object in the loop, and the DOM object does not have access to the text()
method because it is jq_obj's method. Therefore, we need to use a different way to get the inner text to use DOM's method which is innerText
or innerHTML
.
Nevertheless, by wrapping the DOM in $
to convert it to be a jq_obj, we are able to invoke the methods of jq_obj. As a conclusion, the whole samples to solve this trouble is below:
jq_obj.each(function(){
console.log($(this).text());
});
$("li").each(function(){
console.log(this.innerText)
});
for (let x of jq_obj){
console.log(x.textContent);
//textContent is a property of DOM whose value is text of this dom, similar to innerText() method.
}
for (let x of jq_obj){
console.log($(x).text());
}
----------------------------in addition--------------------
it seems that an array function can not transform in each() means.