0

Ok so I had code on a website which has not changed at all. Two days ago I was using this functionality and it worked, but then today while I was testing things it just stopped working.

For some reason changing from the .children() selector to .find() fixed it which I really wasn't expecting.

Here is the code:

var ele = $("div").find("[data-productid='" + response.productId + "']").children(".wishlist-button");
if (response.addedToWishlist) {
    $(ele).children(".button-2.active").removeClass("active");
    $(ele).children(".remove-from-wishlist-button").addClass("active");
}

I know that .children() only selects immediate child so here is the html which illustrates that:

<div class="wishlist-button">
            <input type="button" value="Remove from wishlist" title="Remove from wishlist" class="button-2 remove-from-wishlist-button remove-from-wishlist-button-6475">
            <input type="button" value="Add to wishlist" title="Add to wishlist" class="button-2 add-to-wishlist-button add-to-wishlist-button-6475 active">
    </div>

When I changed the code to this using .find() it worked:

var ele = $("div").find("[data-productid='" + response.productId + "']").find(".wishlist-button");
if (response.addedToWishlist) {
    $(ele).find(".button-2.active").removeClass("active");
    $(ele).find(".remove-from-wishlist-button").addClass("active");
}

Like I said none of the code had changed, so it's strange for it to just stop working. I'm using jquery version 1.10.2 I'm wondering if the .children() function got depreciated, or maybe there is something else going on.

Does anyone know what's going on here? I'm concerned because that .children() function is used hundreds of times throughout the site. Thanks

Web Devvy
  • 55
  • 9
  • Your first code block's text is identical to your third code block's text. Also, I don't see anything in your HTML that would match `[data-productid=...`. No, [.children](https://api.jquery.com/children/) is not deprecated, something else must've changed – CertainPerformance Jan 11 '19 at 03:30
  • Oh sorry will edit – Web Devvy Jan 11 '19 at 03:32
  • @CertainPerformance updated that third code block, you can see I changed children to find – Web Devvy Jan 11 '19 at 03:33
  • `.children(".wishlist-button")` will select only if a `wishlist-button` is a direct child of something matching `[data-productid='" + response.productId + "']`, but the parent of `wishlist-button` is not shown in the HTML, so it's hard to say – CertainPerformance Jan 11 '19 at 03:35
  • Oh I see, the problem was with `var ele = $("div").find("[data-productid='" + response.productId + "']").children(".wishlist-button");` there was an element which was sitting between `.wishlist-button` and the attribute selector element from another dev job. Thanks @CertainPerformance would upvote comment but not enough rep :/ – Web Devvy Jan 11 '19 at 03:39

0 Answers0