CSS Selector with Period in Id

CSS selector with period in ID

After digging through the specs some more, I found the CSS spec does allow for backslash (\) escaping like most languages.

So in my example, the following rule would match:

#some\.id {
color: #f00;
}

How do you select elements in selenium that have a period in their id?

There is incredibly bad development practice. I know you don't have the ability to change it, but if you can, point out that it's very very bad. Why? Two reasons.

In CSS, the rules based on classes generally start with a period.

In CSS selector frameworks, including jQuery/Sizzle and what Selenium is doing in this example, the period has a special meaning - mainly to select elements based on many rules. This is why it's tripping here here - you can see the same thing if you run the CSS selector direct into Chrome or Firebug - it will fall over as well.

Using a period in the ID for your elements is going against all this. Annoyingly the HTML spec allows for this.

Anyway, all is not lost, there are many ways around it.

First, you can escape it:

select#param\\.Status

Second, you could use a slightly more elaborate selector:

select[id='param.Status']

Finally, you could use XPath:

//select[@id='param.Status']

Does querySelectorAll support the period(.) character in an id?

A period in querySelectorAll means you are specifying a css class. In your case querySelectorAll is trying to find out a DOM element with id "my" and having a css class "divid". How will querySelectorAll know that this time you want element by id and not by class? It is up to you to have proper id atrribute so as to no to confuse the method. Though a period is allowed, the best practise is to avoid it most of the time so that you do not confuse other libraries like jquery etc.

JavaFX css id selector with dot (full stop) in name

If you Parse your CSS, you'll see:

    public static void main(String[] args) {
CSSParser cssParser = new com.sun.javafx.css.parser.CSSParser();
Stylesheet s = cssParser.parse("#the\\.button {\n" +
" -fx-graphic: url(\"Keyboard.png\");\n" +
"}\n" +
"\n" +
"#thebutton {\n" +
" -fx-graphic: url(\"Keyboard.png\");\n" +
"}");
System.out.println(""); //add a breakpoint here
}

That there is only one rule for the id thebutton and there is two ways to understand why:

  • One is looking at the source here
  • The other is paying attention to a warning in the documentation here

Which I quote below:

While the JavaFX CSS parser will parse valid CSS syntax, it is not a fully compliant CSS parser. One should not expect the parser to handle syntax not specified in this document.

Emphasis mine

Which means if you are trying something that belongs to the CSS standard, but isn't listed on the Oracle's documentation you are going to get a hard time.

Why is #.id a bad selector in CSS/jQuery yet it works in an HTML anchor?

HTML5 permits having a period in an ID attribute value, and browsers have handled this without any issues for decades (which is why the restriction in HTML 4 — itself defined not by HTML but by SGML on which it is based — was relaxed in HTML5, now free from the legacy baggage of SGML). So the problem isn't in the attribute value.

The grammar of a fragment identifier as defined by RFC 3986 is:

fragment    = *( pchar / "/" / "?" )

Where the character set of pchar includes the period. So .someMethodName is a valid fragment identifier, which is why <a href="#.someMethodName"> works.

But #.someMethodName is not a valid selector, and the reason is twofold:

  1. An ID selector consists of a # followed by an ident, and an ident in CSS cannot contain a period.
  2. The period is therefore reserved for a class selector (which similarly consists of a period followed by an ident).

In short, the parser is expecting a CSS ident after the # but not finding one because of the . that directly follows it, making the selector invalid. This is surprising because the notation of an ID selector is in fact based on the URI notation for a fragment identifier — as evident in the fact that both of them start with a # sign, as well as the fact that they are both used to reference an element uniquely identified within the document by that identifier. It's not unreasonable to expect anything that works in a URI fragment to also work in an ID selector — and in most cases it is true. But because CSS has its own grammar which doesn't necessarily correlate with the URI grammar (because they're two completely unrelated standards1), you get edge cases such as this one.

As the period is part of the fragment identifier, you will need to escape it with a backslash in order to use it in an ID selector:

#\.someMethodName

Don't forget that you need to escape the backslash itself within a JavaScript string (e.g. for use with document.querySelector() and jQuery):

document.querySelector('#\\.someMethodName')
$('#\\.someMethodName')

1 Several years ago a W3C Community Group was formed (of which I am a member) around a proposal known as Using CSS Selectors as Fragment Identifiers that, as you can imagine, married the two technologies in an interesting way. This never took off, however, and the only known implementations are some browser extensions that probably aren't even being maintained.

What are valid values for the id attribute in HTML?

For HTML 4, the answer is technically:

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 (".").

HTML 5 is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.

The id attribute is case sensitive in XHTML.

As a purely practical matter, you may want to avoid certain characters. Periods, colons and '#' have special meaning in CSS selectors, so you will have to escape those characters using a backslash in CSS or a double backslash in a selector string passed to jQuery. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.

For example, the HTML declaration <div id="first.name"></div> is valid. You can select that element in CSS as #first\.name and in jQuery like so: $('#first\\.name'). But if you forget the backslash, $('#first.name'), you will have a perfectly valid selector looking for an element with id first and also having class name. This is a bug that is easy to overlook. You might be happier in the long run choosing the id first-name (a hyphen rather than a period), instead.

You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it firstName or FirstName?" because you will always know that you should type first_name. Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don't mix them.


A now very obscure problem was that at least one browser, Netscape 6, incorrectly treated id attribute values as case-sensitive. That meant that if you had typed id="firstName" in your HTML (lower-case 'f') and #FirstName { color: red } in your CSS (upper-case 'F'), that buggy browser would have failed to set the element's color to red. At the time of this edit, April 2015, I hope you aren't being asked to support Netscape 6. Consider this a historical footnote.

In CSS what is the difference between . and # when declaring a set of styles?

Yes, they are different...

# is an id selector, used to target a single specific element with a unique id, but . is a class selector used to target multiple elements with a particular class. To put it another way:

  • #foo {} will style the single element declared with an attribute id="foo"
  • .foo {} will style all elements with an attribute class="foo" (you can have multiple classes assigned to an element too, just separate them with spaces, e.g. class="foo bar")

Typical uses

Generally speaking, you use # for styling something you know is only going to appear once, for example, things like high level layout divs such sidebars, banner areas etc.

Classes are used where the style is repeated, e.g. say you head a special form of header for error messages, you could create a style h1.error {} which would only apply to <h1 class="error">

Specificity

Another aspect where selectors differ is in their specificity - an id selector is deemed to be more specific than class selector. This means that where styles conflict on an element, the ones defined with the more specific selector will override less specific selectors. For example, given <div id="sidebar" class="box"> any rules for #sidebar with override conflicting rules for .box

Learn more about CSS selectors

See Selectutorial for more great primers on CSS selectors - they are incredibly powerful, and if your conception is simply that "# is used for DIVs" you'd do well to read up on exactly how to use CSS more effectively.

EDIT: Looks like Selectutorial might have gone to the big website in the sky, so try this archive link instead.

Handling a colon in an element ID in a CSS selector

Backslash:

input#search_form\:expression {  ///...}
  • See also Using Namespaces with CSS (MSDN)


Related Topics



Leave a reply



Submit