views:

29

answers:

2

I'm trying to select a div with the id "about me". I think I am having problems because of the spaces.

alert($link.attr("title"));

I get "about me"

alert($('#'+$link.attr("title")).attr("title"));

I get undefined.

I have tried to use php and jquery methods for removing them but it doesn't work.

So how do I get around this?

+2  A: 

You need to remove the spaces, IDs with spaces aren't valid, and you'll have all sorts of issues...just like this :)

You can escape it like this:

alert($('#'+$link.attr("title").replace(/ /g, "\\ ")).attr("title"));

But this is not the correct solution to the problem, removing the spaces is the correct approach.

Nick Craver
A: 

In general, if you want to get an element by a variable ID it's better to do that via the plain DOM getElementById method than to try to shoehorn it into a selector with all the escaping issues that brings with it. eg:

$(document.getElementById($link.attr("title")))

However, for the particular case of the space character, it's invalid, period; as Nick says, you need to get rid of it. Whilst IDs are much more permissive in HTML5 than they were in HTML4 and XHTML1, even in HTML5 spaces are not allowed.

bobince