简体   繁体   中英

why i'm getting a querySelectorAll() error

i tried to implement a document.getElementsByAttribute function and i came with this :

function getElementsByAttribute(att, val){

    return document.querySelectorAll(`[${att} = ${val}]`)

}

but why i get an error when i try to type the return statement directly on the console :

document.querySelectorAll("["id" = "btn"]")

is it not the same like getElementsByAttribute2('id', 'btn') ?

but why i get an error when i try to type the return statement directly on the console :

document.querySelectorAll("["id" = "btn"]")

Because what you are typing into the console is not the same as what you have in your function. Your function uses template literals :

document.querySelectorAll(`[${att} = ${val}]`)

And, template literals can be inserted directly into regular literal strings without having to worry about quoting them or concatenating them with the rest of the string.

When you enter directly into the console, you didn't use template literals, you just used a literal and in that case quotes and concatenation matter. Quotes come in pairs, so the first pair is: "[" and that is immediately followed by id and because you didn't concatenate the two parts like this:

"[" + id

It throws an error - probably something like unexpected identifier .

The CSS attribute selector should take the form of:

[attributeName comparisonOperator value]

Quotes around the value are only necessary if the value has spaces in it. So you could just write:

document.querySelectorAll("[id=btn]");

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