简体   繁体   English

如何将querySelectorAll与变量一起使用?

[英]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). 我有两个互为替代的HTML元素,并且我试图编写一个JS函数,如果存在另一个,则将其删除(它们源自TEI文档中<choice><choice> <sic><corr>单词) 。 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: 在我的转换中,它们都被分配了一个具有唯一前缀的代码( 不是 @id@id是随机生成的,必须保留以用于其他目的):

<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. 在“属于” Element1的JS函数中,我想选择Element2以便将其删除。 This is what I have tried ( el is element1): 这是我尝试过的( el是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. 这可能会失败,大概是因为最后一行的corrID变量位于引号中,并且被视为字符串。 I have read various tutorials on CSS selectors and can't find any guidance on how to use them with a variable attribute value. 我已经阅读了有关CSS选择器的各种教程,但是找不到关于如何将它们与可变属性值一起使用的指南。 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. 编辑:有人建议将其他与如何在JS中将字符串与变量连接在一起的其他问题,作为此问题的重复。 To clarify, I am asking specifically about querySelectorAll , as I cannot find any examples this being used with variables. 为了澄清,我专门询问querySelectorAll ,因为我找不到与变量一起使用的任何示例。 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. 如果答案是将其选择器视为任何其他JS字符串(即可以串联变量),那么这是完全令人满意的。

使用模板文字评估

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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