Home > Net >  how to query a css selector with an attribute name starting with '@'?
how to query a css selector with an attribute name starting with '@'?

Time:12-05

I use $('div[@click="login()"]') to select

<div @click="login()"> Login </div>

but it gives

VM353:1 Uncaught DOMException: Failed to execute '$' on 'CommandLineAPI': 'div[@click="login()"]' is not a valid selector.
    at <anonymous>:1:1

what is the correct way?

CodePudding user response:

The element <div @click="login()"> Login is not valid HTML because it contains an attribute name that starts with the @ symbol. In HTML, the @ symbol is used to denote at-rules, which are rules that apply to the entire document or a group of rules. Therefore, using the @ symbol in an attribute name is not valid, and it will result in an error.

To specify an attribute with a name that starts with the @ symbol in HTML, you need to escape the @ symbol by preceding it with a \ character. For example, you can use the following element to specify an attribute with the @click name:

<div \\@click="login()"> Login </div>

In this case, the \@ character tells the parser to treat the @ symbol as a literal character, rather than as an at-rule. This will allow you to specify attributes with names that start with the @ symbol.

It's worth noting that using attributes with names that start with the @ symbol is not recommended, as it can lead to confusion and potential errors. In general, it's best to avoid using the @ symbol in attribute names, and to use a different character, such as - or _, instead.

CodePudding user response:

That's not valid HTML.

You're probably using a templating language (e.g. EJS, Pug, Handlebars, React, Angular) that transpiles to HTML.

Try $('div[onclick="login()"]'). Maybe it will return you the element you want (my guess is that @click will become onclick on the actual webpage.)

Otherwise, give your div an id too:

<div id="my-div" @click="login()"> Login </div>

And select on that id: $('#my-div')

  • Related