1

I have dynamic ID that has been passed through a variable. Unfortunately when try to reference it into the querySelectorAll I am getting an error:

Failed to execute 'querySelectorAll' on 'Document':'#paragraph-1 .is-available"' is not a valid selector.

My code is below

var x = ('"#' + dataID + ' is-available"');
var test = document.querySelectorAll (x);
console.log(test);

When I look into the console log it outputs it correctly to:

#paragraph-1 .is-available

Any idea as to how I should be referencing the variable into my querySelectorAll?

2
  • 4
    get rid of those " - i.e. var x = ('#' + dataID + ' is-available'); because the string #paragraph-1 .is-available is valid, but the string "#paragraph-1 .is-available" is not (though, from the error you've shown, the code isn't exactly what you claim it is) - var x = ('"#' + dataID + ' is-available"'); would result in something like "#paragraph-1 is-available" but the error is that #paragraph-1 .is-available" is invalid Commented Jul 23, 2018 at 22:57
  • And note that it needs to be .is-available and not just is-available
    – Pointy
    Commented Jul 23, 2018 at 22:59

1 Answer 1

5

Two things:

  1. Get rid of the double quotes in your selector
  2. Add replace the white space with a . in your selector for is-available.

You should get a proper result with this selector:

document.querySelectorAll('#' + dataID + '.is-available');

Update:

It is unclear whether you want to select all child elements of the element with the specified ID or all elements that have the specified ID and class. Keep the white space and add . to is-available if child elements are to be selected. Making your code as follows:

document.querySelectorAll('#' + dataID + ' .is-available');
2
  • look at the error ... look at the code ... see how the code could not possibly produce the error Commented Jul 23, 2018 at 23:00
  • 3
    Where in the post does it say that the is-available is not a child of the id?
    – Taplar
    Commented Jul 23, 2018 at 23:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.