Skip to main content

jQuery Selector is Referencing CSS Elements, Why?

By Sam Deering

JavaScript

Share:

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

Question

“jQuery Selector is Referencing CSS Elements, Why?”

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

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

Integromat Tower Ad