Lizard
Lizard

Reputation: 45002

Using the # inside a CSS id declaration

Normally i would only use alphanumeric with - and _ in any html class or id attribute, but i wondered whether it was possible it include a # in the middle of an attribute, e.g:

<div id = "my_css_id_#f4ed11">

I wont't be a targeting this through CSS, this is purely for javasrcipt.

NOTE The reason I am asking it not because I want to do this, but because of some related PHP code done by someone it would make this part of the project easier.

Thanks

Upvotes: 1

Views: 241

Answers (3)

dangerChihuahua007
dangerChihuahua007

Reputation: 20895

I wouldn't recommend doing that. It would be difficult to access an element with ID #...#... via CSS or even Javascript as you noted since # is so overloaded in programming/coding.

It sounds like you want to store some piece of data. You are aware that W3C standards allow attributes that begin with data- right?

For instance, you could keep a piece of data associated with an element as such:

<p data-name="John Jones">I like alliteration.</p>

This article details data attributes effectively. http://ejohn.org/blog/html-5-data-attributes/

Upvotes: 1

Mathias Bynens
Mathias Bynens

Reputation: 149564

Sure you can. It’s valid as per HTML5.

You’ll simply need to escape the character in a selector (for use in CSS or JavaScript). For the # character, it’s quite simple; you can just use \#.

Here’s a tool that will tell you how to escape any character in a CSS/JS selector: http://mothereff.in/css-escapes#0foo%23bar From that page:

<script>
  // document.getElementById or similar
  document.getElementById('foo#bar');
  // document.querySelector or similar
  $('#foo\\#bar');
</script>

P.S. On the subject of weird characters in ID or class values: http://mathiasbynens.be/notes/html5-id-class

Upvotes: 4

Chris Cates
Chris Cates

Reputation: 75

It would be best to do trial and error and see if it works. But, in terms of pseudo-selectors, there should be no problem with have the # symbol. To select you would use:

$("#my_css_id_#f4ed11")

Upvotes: 0

Related Questions