JavaScript
Article
By Sam Deering

jQuery Selector is Referencing CSS Elements, Why?

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Hi guys, I have recently had this question so thought I would share it with you!

Question

“jQuery Selector is Referencing CSS Elements, Why?”

--ADVERTISEMENT--

Answer

jQuery elements may include css naming schemes in IDs and they may be are interpreted as CSS notation
(particularly when using colons “:” and periods “.”). jQuery ID attributes may contain periods, colons, letters, numbers, hyphens, and underscores. The answer is to escape these characters by placing two backslashes in front of them.

For example:

// Does not work
$("#some:id")
 
// Works!
$("#some\:id")
// Does not work
$("#some.id")
 
// Works!
$("#some\.id")

Fix it with a function!

function jq(myid) { 
	return '#' + myid.replace(/(:|.)/g,'\$1');
}

//usage:
$( jq('some.id') )
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?