Is it safe to use # and. characters in html attributes?

I am wondering if I can set the attribute value of an HTML object as a string containing the # character?

The reason I want to do this is because there will be many elements on the page that should scroll to the specified elements, and I want to save the data, which element should be scrolled to? 'as attribute data-scrollto.

So, my JavaScript code will look like this:

 function ScrollToElement(lm) { var theTop = lm.offset().top; $("html,body").animate({ scrollTop: theTop/*, scrollLeft: 1000*/ }); } // .. and add click event to all such objects : $('.scroller').click(function(){ var theSelector = $(this).attr('data-scrollto'); ScrollToElement($(theSelector)); }); 

so the html elements will look like this:

 <a class='scroller' data-scrollto='p#p-to-scroll'>Click to scroll to p</a> 

safely?

And as a side question, why

 $(element).data('scrollto'); 

doesn't work but

 $(element).attr('data-scrollto'); 

works?

+4
source share
2 answers

According to the W3C specifications, yes, it is safe to use the U+0023 NUMBER SIGN ( # ) characters and the U+002E FULL STOP ( . ) U+002E FULL STOP .

The name of the attribute, followed by zero or more spaces, followed by one character U+003D EQUALS SIGN , followed by zero or more spaces, followed by the value of the attribute, which should not, in addition to the requirements given above for attribute values contain literal space characters, any characters U+0022 QUOTATION MARK ( " ), U+0027 APOSTROPHE ( ' ), U+003D EQUALS SIGN characters ( = ), U+003C LESS-THAN SIGN characters (), U+003E GREATER-THAN SIGN characters ( > ) or U+0060 GRAVE ACCENT characters (`) and must not be an empty string .

Read http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#attributes-0 .

+3
source

Yes, you can save the hash # and . in data attributes. You must use proper data methods. http://api.jquery.com/jQuery.data/

 var theSelector = $(this).data('scrollto'); 

If you cannot use the data method, check the jQuery version you are using, it was introduced in version 1.2.3

0
source

Source: https://habr.com/ru/post/1500345/


All Articles