henryprescott
henryprescott

Reputation: 483

jquery selector problem

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?

Upvotes: 0

Views: 57

Answers (2)

bobince
bobince

Reputation: 536379

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.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630409

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.

Upvotes: 2

Related Questions