Search code examples
domdocumentselectors-api

document.querySelectorAll to find item based on multiiple condition?


I am trying to find div based on combination of class name and data attribute. But it doesn't seems to returning any value.

var products = document.querySelector("div.productDisplay").querySelectorAll("[data-productId='" + id  + "']");

Solution

  • The first .querySelector() call will only return a single element. If that does not match the selector in the querySelectorAll() call then no elements will be retured.

    Try using a single selector, such as:

    var products = document.querySelector("div.productDisplay[data-productId='" + id  + "']");