1

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 (i.e. variables can be concatenated in), then that is perfectly satisfactory.

5

1 Answer 1

2

Use template literals to evaluate that

var corr = document.querySelectorAll(`a[choicePOS=${corrID}]`);
Sign up to request clarification or add additional context in comments.

12 Comments

I believe you meant document.querySelectorAll(`a[${choicePOS}=${corrID}]`)
You should've kept @lonesomeday's edit. Now it's broken again.
His edit was `a[choicePOS=${corrID}]` because corrID is the variable to be added to the string. The data-attribute is named choisePOS. If you use @skyboyer's version, the selector will be attempting to select "0=corr0".
Nope, still broken. Now you're back to @skyboyer's broken version. How does this keep getting upvotes?
@EysteinThanisch Then try normal string concatenation, like this document.querySelectorAll('a[choicePOS=' + corrID + ']' );
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.