Search code examples
javascriptclassselectors-api

.querySelectorAll how to take only elements with all attributes


If i have that string:`

document.querySelectorAll("[data-name=" + CSS.escape(variable) + "]","[class='nameclass']");

It takes all elements with the first attribute and all elements with the second attribute.

How I have to do for take only elements with each attributes?


Solution

  • It seems you are looking for this selector:

    document.querySelectorAll(".nameclass[data-name=" + CSS.escape(variable) + "]");
    

    Please note that I have used .nameclass as a class selector which differs from [class=nameclass]. The first one selects the elements that one of their classes is nameclass and the second one selects elements that have just nameclass class attribute.

    If the elements that have just nameclass class attribute should be selected, the selector should be:

    "[class=nameclass][data-name=" + CSS.escape(variable) + "]"