Search code examples
javascriptselectors-api

How to simplify querySelectorAll parameter using value of another querySelectorAll


I have the following:

var searchSuggestionsItems = document.querySelectorAll("#search-user-results .live-search-results--list li");

And want to use this selector for select all a elements that have .overedSuggestion class. I know that the following should work:

var selectedSuggestion = document.querySelectorAll("#search-user-results .live-search-results--list li a.overedSuggestion");

But I'm looking for a simplified way to do. What I tried:

selectedSuggestion = document.querySelectorAll(searchSuggestionsItems+' a.overedSuggestion');

this returns the following error:

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '[object NodeList] a.overedSuggestion' is not a valid selector.

Solution

  • That's because you are concatenating a NodeList collection with a string. The NodeList is converted to [object NodeList] string which is not a valid/meaningful selector.

    DOM elements also have .querySelectorAll method, so you can code:

    searchSuggestionsItems[0].querySelectorAll('a.overedSuggestion');
    

    The above code snippet returns a.overedSuggestion descendants of the first element in the node list. For getting descendants of all the elements in the list you need to iterate through the list which is not efficient. Using a longer selector is more efficient.

    Your code would work if searchSuggestionsItems was a selector, i.e.:

    var searchSuggestionsItems = "#search-user-results .live-search-results--list li";