John
John

Reputation: 619

Invalid selector on 'querySelectorAll' using variable for the id

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?

Upvotes: 1

Views: 927

Answers (1)

Ashton French
Ashton French

Reputation: 370

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');

Upvotes: 5

Related Questions