简体   繁体   中英

inserting a variable in a querySelectorAll() doesn't work

I made a for-loop to execute some code for multiple elements in an array. There is a querySelectorAll() in this for-loop but since the querySelectorAll() needs to work with a diffirent element every loop, i tried to insert a variable in it, but that gives me an error. When i put in the exact output of that variable straight into the querySelectorAll() it does work. Does anyone know how to fix this?

(1) This is the code when it does work, but as I said, the actual className needs to change. That's why I want to insert a variable.

var tipSelectors0 = document.querySelectorAll(".tipContainer0 .pageContent-exercise-help-model-tip-select-container-li");

(2)This is the code that doesn't work. But as you can see in the comment and in the console. The variable output is exactly the same as what I put in by code (1).

    Line637 var tipContainerClassName = "tipContainer" + j; //j = 0
    Line638 var newClassName ='".' + tipContainerClassName + ' .pageContent-exercise-help-model-tip-select-container-li"';
    Line639 console.log(newClassName); //Outputs:   ".tipContainer0 .pageContent-exercise-help-model-tip-select-container-li"
    Line640 var tipSelectors0 = document.querySelectorAll(newClassName);

(3) This is the error I get in the console using code (2)

".tipContainer0 .pageContent-exercise-help-model-tip-select-container-li" Leerstof.html:639
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '".tipContainer0 .pageContent-exercise-help-model-tip-select-container-li"' is not a valid selector. Leerstof.html:640

Thanks!

There is no need to use quotes in the selector itself. You just need to remove the double quotes:

'.' + tipContainerClassName + ' .pageContent-exercise-help-model-tip-select-container-li'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM