简体   繁体   中英

How to use querySelectorAll with a variable?

I have two HTML elements that are alternatives of each other and I am trying to write a JS function that removes one if the other is present (they originated as words within <sic> and <corr> beneath <choice> in a TEI document). In my transformation, they are both assigned a code ( not an @id : @id is randomly generated and has to remain so for other purposes) with a unique prefix:

<a id="abc" choicePOS="sic0">Element1</a>
<a id="xyz" choicePOS="corr0">Element2</a>

In a JS function that 'belongs' to Element1, I want to select Element2 so as to remove it. This is what I have tried ( el is element1):

var choicePOS = el.getAttribute("choicePOS").slice(3); // produces 0
var corrID = "corr" + choicePOS; // produces corr0
var corr = document.querySelectorAll("a[choicePOS=corrID]");

This fails, presumably because the corrID variable in the last line is in quote marks and is being taken as a string. I have read various tutorials on CSS selectors and can't find any guidance on how to use them with a variable attribute value. Is this possible? If so, how? If not, any alternatives?

EDIT: A number of other questions relating how to concatenate strings with variables in JS have been suggested as duplicates of this one. To clarify, I am asking specifically about querySelectorAll , as I cannot find any examples this being used with variables. If the answer is that its selector is to be treated as any other JS string (ie variables can be concatenated in), then that is perfectly satisfactory.

使用模板文字评估

var corr = document.querySelectorAll(`a[choicePOS=${corrID}]`);

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