admin管理员组

文章数量:1394585

Is it possible to use a dot in a classname inside Jquery?

$('.B.Avf').toggle();

I need to keep the dot in: B.Avf classname.
Can i somehow escape it?
Is this possible?

UPDATE

I tried to escape it with "\" with no success.

Is it possible to use a dot in a classname inside Jquery?

$('.B.Avf').toggle();

I need to keep the dot in: B.Avf classname.
Can i somehow escape it?
Is this possible?

UPDATE

I tried to escape it with "\" with no success.

Share Improve this question edited Oct 1, 2015 at 15:14 Björn C asked Oct 1, 2015 at 14:58 Björn CBjörn C 4,00811 gold badges52 silver badges87 bronze badges 8
  • 4 Escape it by preceding with \\. $('.B\\.Avf').toggle(); – Tushar Commented Oct 1, 2015 at 14:58
  • Hmm.... i dont think it works. Because my filter wont work. If i change the class to something whitout a dot.. it works... – Björn C Commented Oct 1, 2015 at 15:02
  • 2 You can use the [attr="val"] selector: $('[class*="B.Avf"]'). – gen_Eric Commented Oct 1, 2015 at 15:06
  • 3 Don't use dots in your class names...? – Evan Davis Commented Oct 1, 2015 at 15:07
  • @Mathletics Well. sometimes you dont have the choice! – Björn C Commented Oct 1, 2015 at 15:08
 |  Show 3 more ments

2 Answers 2

Reset to default 5

You can always just use the [attr="val"] selector for this.

$('[class*="B.Avf"]')

The *= means "class contains...". Since this is looking at the attribute directly and there could be more than one class, you don't want to use =.

There are two ways to select elements that have special selection characters in their identifiers. As Tushar mentioned in a ment, you can use a double backslash (\\) to escape the special character in query (including both jQuery and document.querySelector), or you can use an attribute selector, as Rocket Hazmat pointed out.

Note that in CSS (that is, an actual stylesheet, not JavaScript), the selector is slightly different. You only need a single backslash to escape the special characters.

Demo below:

// use a double backslash to escape characters in JavaScript query selectors
document.querySelector(".a\\.b").style.backgroundColor = "blue";

//or use an attribute selector!
document.querySelector('[class="a.b"]').style.color = "white";
/* Use a single backslash to escape characters in CSS */
.a\.b{border:1px solid black;}
<div class="a.b">My class name is a.b</div>

本文标签: javascriptUse a dot in a class name within jquery (39BAvf39)toggle()Stack Overflow