Using the # inside a CSS id declaration - javascript

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

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

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/

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

Related

What is this HTML notation and how can I use it myself?

AddThis uses a notation which seems to extend the parameters available in an HTML div tag.
The tag that contains the button array can include additional parameters such as:
<div addthis:url="someUrl"> </div>
Along with defining some css classes for the element seems to give their JavaScript code access to manipulate this element AND read the value of the additional addthis: parameter.
I'd like to implement something similar myself but am confused as to how to correctly allow additional parameters in the standard HTML tags.
I've also seen the AddThis code throw W3C validation errors sometimes so wonder if this is entirely legitimate.
Searching around I've found some discussions about extending the HTML tags via extending the prototypes in JavaScript but everything I've read seems to be about adding new events etc.
This addthis:url notation looks more 'schema'-like to me, or am I on completely the wrong track?
I've made some progress on this, at least functionally, but what I have now breaks the HTML validation quite seriously.
To explain a little further what I am trying to achieve...
In the same way that AddThis allows you to include their sharing elements by adding a simple <DIV> tag to your page and including some JavaScript, I want to provide similar functionality with <IMG> tags.
Someone wanting to use this functionality will include an <IMG> tag that has some additional name=value pairs that are outside of the standard image tags attribute and are defined by my spec.
The JavaScript that is included will then read these additional attributes and perform some actions on the image tags.
To this end I have the following:
<IMG id="first image" class="imageThatCanBeWorkedOn" src="holding.png"
my-API-name:attribute1="some data"
my-API-name:attribute2="some other data">
I then use `getAttribute('my-API-name:attribute1') to access the additional tag data from JavaScript.
(I'm selecting all of the tags with a particular class name into an array and then processing each tag in turn, in case anyone is interested.)
This all works great - I can manipulate the <IMG> tags as needed based on the additional data, BUT the markup is not valid HTML according to the W3C validator.
With the above I get:
Warning Attribute my-API-name:attribute1 is not serializable as XML 1.0.
Warning Attribute my-API-name:attribute2 is not serializable as XML 1.0.
Error: Attribute my-API-name:attribute1 not allowed on element img at this point.
Error: Attribute my-API-name:attribute2 not allowed on element img at this point.
If I remove the : from the attribute name (eg my-API-name-attribute2) the 'not serializable' warnings disappear but I still get the 'not allowed' errors.
So how would I add these additional bits of data to an <IMG> tag and not invalidate the markup but while maintaining a level of clarity/branding by including the 'my-API-name' part in the way that AddThis does?
(I note from the comments that I could use data- attributes. I haven't tried these yet, but I'd prefer to be able to do this in the 'branded' way that AddThis seems to have managed without breaking their users' markup.)
If we were talking about XML (which includes XHTML) it'd be a namespace prefix. In HTML5 it's just a regular attribute:
Attribute names must consist of one or more characters other than the
space characters, U+0000 NULL, U+0022 QUOTATION MARK ("), U+0027
APOSTROPHE ('), U+003E GREATER-THAN SIGN (>), U+002F SOLIDUS (/), and
U+003D EQUALS SIGN (=) characters, the control characters, and any
characters that are not defined by Unicode.
... though slightly harder to manipulate (not too much, though) and totally non-standard.
I'd like to implement something similar myself but am confused as to
how to correctly allow additional parameters in the standard HTML
tags.
Before HTML5, some web developers deployed a technique of adding custom data to an element's class attribute (or to any other attribute which will happily attach itself to any element).
This worked, but it was self-evidently a hack.
For this reason HTML5 introduced custom data-* attributes as the standard approach to extending an element's attributes - and data-* is precisely what you should be deploying.
So how would I add these additional bits of data to an tag and
not invalidate the markup but while maintaining a level of
clarity/branding by including the 'my-API-name' part in the way that
AddThis does?
<img id="first image" class="imageThatCanBeWorkedOn" src="holding.png"
data-myAPIName_attribute1="some data"
data-myAPIName_attribute2="some other data" />
Further Reading:
Time Travel back to 2010: http://html5doctor.com/html5-custom-data-attributes/
Time Travel back to 2008: http://ejohn.org/blog/html-5-data-attributes/

Are there reserved names for JQuery Selectors?

I had an accidentally misspelled selector like this:
$("#cut")
And it was NOT retrieving the object appropriately; I definitely had an object with that id defined on the HTML that existed. I tried changing the object's id (and the selector's call) and it worked like a charm, so I'm 99% I somehow can't use $("#cut") as selector.
Are there any other cases that might be interesting to learn?
Thanks a lot
EDIT: I misspelled the selector as $("#cut#") here once, that's an error here, it was not like that on the code. Sorry for that!
Q: "Are there reserved names for JQuery Selectors?"
A: No.
Wish there was a more in-depth answer for you, but that's pretty much the gist of it.
For more information on valid jQuery selectors, check out their docs here.
Yes you are correct. #cut# is not a valid selector - hence why jQuery can not find it. But stripping the last # will make it a valid selector.
The question is really what type of values the id attribute on an HTML element will allow. The hash-sign is definitely one of the reserved characters.

regex to change text inside a html tag

First of all I'm new to stackoverflow so I'm sorry if I posted this in the wrong section.
I need a regex to search within the html tag and replace the - with a _
e.g:
<TAG-NAME>-100</TAG-NAME>
would become
<TAG_NAME>-100</TAG_NAME>
note that the value inside the tag wasn't affected.
Can anyone help?
Thanks.
Since JavaScript is the language for DOM manipulation, you should generally consider parsing the XML properly and using JavaScript's DOM traversal functions instead of regular expressions.
Here is some example code on how to parse an XML document so that you can use the DOM traversal functions. Then you can traverse all elements and change their names. This will automatically exclude text nodes, attributes, comments and all other annoying things, you don't want to change.
If it has to be a regex, here is a makeshift solution. Note that it will badly fail you if you have tags (or even only >) inside attribute names or comments (in fact it will also apply the replacement to comments):
str = str.replace(/-(?=[^<>]*>)/g, '_');
This will match a - if it is followed by a > without encountering a < before. The concept is called a negative lookahead. The g modifier makes sure that all occurrences are replaced.
Note that this will apply the replacement to anything in front of a >. Even attribute values. If you don't want that you could also make sure that there is an even number of quotes between the hyphen and the closing >, like this:
str = str.replace(/-(?=[^<>"]*(?:"[^<>"]*"[^<>"]*)*>)/g, '_');
This will still change attribute names though.
Here is a regexpal demo that shows what works and what doesn't work. Especially the comment behavior is quite horrible. Of course this could be taken care of with an even more complex regex, but I guess you see where this is going? You should really, really use an XML parser!
s/(\<[^\>]+\>)\-([^\<]+\<\/)/\1_\2/
Although I am not familiar with JS libraries, but I am pretty sure there would be better libraries to parse HTML.

Is there a way to create your own HTML element?

Is there a way to create your own HTML element? I want to make a specially designed check box.
I imagine such a thing would be done in JavaScript. Something akin to document.createHTMLElement but the ability to design your own element (and tag).
No, there isn't.
The HTML elements are limited to what the browser will handle. That is to say, if you created a custom firefox plugin, and then had it handle your special tag, then you "could" do it, for varying interpretations of "doing it". A list of all elements for a particular version of HTML may be found here: http://www.w3.org/TR/html4/index/elements.html
Probably, however, you don't actually want to. If you want to "combine" several existing elements in such a way as they operate together, then you can do that very JavaScript. For example, if you'd like a checkbox to, when clicked, show a dropdown list somewhere, populated with various things, you may do that.
Perhaps you may like to elaborate on what you actually want to achieve, and we can help further.
Yes, you can create your own tags. You have to create a Schema and import it on your page, and write a JavaScript layer to convert your new tags into existing HTML tags.
An example is fbml (Facebook Markup Language), which includes a schema and a JavaScript layer that Facebook wrote. See this: Open Graph protocol.
Using it you can make a like button really easily:
<fb:like href="http://developers.facebook.com/" width="450" height="80"/>
The easiest way would be probably to write a plugin say in Jquery (or Dojo, MooTools, pick one).
In case of jQuery you can find some plugins here http://plugins.jquery.com/ and use them as a sample.
You need to write own doctype or/and use own namespace to do this.
http://msdn.microsoft.com/en-us/magazine/cc301515.aspx
No, there is not. Moreover it is not allowed in HTML5.
Take a look at Ample SDK JavaScript GUI library that enables any custom elements or event namespaces client-side (this way XUL for example was implemented there) without interferring with the rules of HTML5.
Take a look into for example how XUL scale element implemented: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/elements/scale.js and its default stylesheet: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/themes/default/input.css
It's a valid question, but I think the name of the game from the UI side is progressive markup. Build out valid w3 compliant tags and then style them appropriately with javascript (in my case Jquery or Dojo) and CSS. A well-written block of CSS can be reused over and over (my favorite case is Jquery UI with themeroller) and style nearly any element on the page with just a one or two-word addition to the class declaration.
Here's some good Jquery/Javascript/CSS solutions that are relatively simple:
http://www.filamentgroup.com/examples/customInput/
http://aaronweyenberg.com/90/pretty-checkboxes-with-jquery
http://www.protofunc.com/scripts/jquery/checkbox-radiobutton/
Here's the spec for the upcoming (and promising) JqueryUI update for form elements:http://wiki.jqueryui.com/Checkbox
If you needed to validate input, this is an easy way to get inline validation with a single class or id tag: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Ok, so my solution isn't a 10 character, one line solution. However, Jquery Code aside, each individual tag wouldn't be much more than:
<input type="checkbox" id="theid">
So, while there would be a medium chunk of Jquery code, the individual elements would be very small, which is important if you're repeating it 250 times (programmatically) as my last project required. It's easy to code, degrades well, validates well, and because progressive markup would be on the user's end, have virtually no cost on the server end.
My current project is in Symfony--not my choice--which uses complex, bulky server-side tags to render form elements, validate, do javascript onclick, style, etc. This seems like what you were asking for at first....and let me tell you, it's CLUNKY. One tag to call a link can be 10 lines of code long! After being forced to do it, I'm not a fan.
Hm. The first thought is that you could create your own element and do a transformation with XSLT to the valid HTML then.
With the emergence of the emerging W3 Web Components standard, specifically the Custom Elements spec, you can now create your own custom HTML elements and register them with the parser with the document.register() DOM method.
X-Tag is a helpful sugar library, developed by Mozilla, that makes it even easier to work with Web Components, have a look: X-Tags.org

Is it OK to add your own attributes to HTML elements? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Custom attributes - Yay or nay?
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
In current learning project I am working on, I need to add an attribute whose value will be a number. At first I thought of using "id" for this purpose but an answer revealed that it is not good to do that.
Is it OK if I create my own attribute, say "messid" and assign a numeric value such as "12", "6" etc to it?
Here is why I want to do this so that you can correct me if I am doing it totally wrong:
I need to access this number in my JavaScript (using jQuery). Just taking the value of attribute is easy but extracting the numeric value from a string like "m12" or "m6" is a pain. (I am a beginner in JavaScript world.)
There has been much discussion about this:
Custom attributes - Yay or nay?
How to store arbitrary data for some HTML tags
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
At the end of the day, I am on the camp that believes data attributes are the best way to go. They are being introducted in HTML5 to avoid name conflicts. Essentially, if you want to store anything data related you just prepend "data-" on the attribute name:
<div class="user" data-userid="5"></div>
The only con to the whole thing is then that your XHTML won't validate, but I honestly don't care about that stuff. (That's right, I said it)
In HTML 5 you're allowed to add any attribute starting with data-, so e.g. <div data-messid="12"> is OK.
HTML 4 and XHTML 1 won't validate if you add your own attribute, but besides that nothing bad will happen if you choose attribute name unique enough (so it won't conflict with any current or future HTML attribute).
Just so you know, you can easily extract an ID from a string like m12 or m6, I would do it like this:
//name the IDs m_12, m_3 etc
var number = $('#someElement').attr('id').split('_')[1];
Or if say, you have a bunch of links with numbers in the ID as above, and all the links have the clickMe class:
$('a.clickMe').click(function() {
alert($(this).attr('id').split('_')[1]);
});
I use custom attributes, and since they are supported by all browsers I checked I think it is not bad to use them. You can also use custom HTML tags to simulate HTML5, with some IE hack, so why not use attributes, if they don't need any hacks?
Anyway, you can read similar discussion here:
Custom attributes - Yea or nay?
This isn't a definitive answer, but having had to do this in the past I can say this not only works well, it is cross-browser friendly.
If using jQuery you can use .data to store custom information against an element.
The downside of custom attributes are:
IE6 creates extra objects to store custom 'expando' attributes these have a tendency to leak especially if they are created via script.
validation issues
No - it's not.

Categories