简体   繁体   中英

jQuery: Selecting Elements by Class Returning jQuery.fn.init(9) - Cannot Read .val()

I am trying to obtain all elements with a certain class name using the following code:

productPrices = $('.product-price');

However this is returning:

jQuery.fn.init(9) [div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, div.product-price, prevObject: jQuery.fn.init(1)]

I believe this is why I cannot access the value of each index; when I try to execute this code:

    // Clone original prices
for(var i = 0; i < productPrices.length; i++) {
    productPrices[i].val().replace("£", "");
    console.log(productPrices[i].textContent);
    britishPrices[i] = productPrices[i].textContent;
}

I get the following error:

productPrices[i].val is not a function

As I said, I believe this is being caused by a strange return value when selecting the class values. I have also tried using .text() as well as .html() too.

If anyone could aid my understanding on this I would be extremely grateful.

productPrices[i]

should be

productPrices.eq(i)

Bracket notation on a jQuery object breaks the DOM Element out of the result stack and it is no longer a jQuery object, which val() is a method of. To keep it as a jQuery object, use eq(#) instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM