How to escape id containing <b>

时间:2016-08-23 15:32:30

标签: jquery jquery-selectors escaping

I'm trying to escape this (German) id CSS selector in jQuery (note the <b>):

$('[id="fa_form_row_<b>Wer ist der teilnehmer/in (Mehrfachantworten möglich)?</b> des Kurses:"]').toggleClass('inactive');

How can I do this?

2 个答案:

答案 0 :(得分:1)

Even if you can do this, you shouldn't. As you can see from the MDN docs, the id attribute cannot contain these some of the characters you already have:

This attribute's value must not contain whitespace (spaces, tabs etc.).

And:

Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.

The official HTML spec confirms this:

The value must not contain any space characters.

And for HTML4:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

答案 1 :(得分:1)

Just use (double) backslashes:

$('[id="fa_form_row_\\<b\\>Wer ist der teilnehmer/in (Mehrfachantworten möglich)?\\</b\\> des Kurses:"]').toggleClass('inactive');

(Source: CSS Tricks)


Also check out CSS.escape(), an experimental technology that has some support in Chrome and Firefox:

var selector = CSS.escape('[id="fa_form_row_<b>Wer ist der teilnehmer/in (Mehrfachantworten möglich)?</b> des Kurses:"]');
$(selector).toggleClass('inactive');