How to fix this issue?

Hi,

today I come up to a strange problem I couldn’t find a solution for. I have a div which has a hash in its id. Normally I fetch elements with jQuery using

let el = $('#id);

but if the id of the element is like

<div id = "test#test"></div>

this doesn’t work

Is there any workaround?

Don’t do that?

Seriously, though. The valid values for id attributes are letters, numbers (though they can’t START with numbers), dashes and underscores. A hash/pound sign is not a valid value.

OK, technically, anything but white spaces are allowed, but you have to escape them, which is a right royal pain…

Is a hash allowed in an id? I can see it could cause some confusion, referring to it as #test#test for example.

Edit: bum, ninja’d.

1 Like

At the end the idea of the hash is not from me :slight_smile: You see there are designers and programmers :smiley:

But I will ask if they can change it.

Thanks

2 Likes

You can do it like this using the attribute selector instead:

console.log($("[id='test#test']").attr("id"));

Html5 does technically allow anything except whitespace for an ID but it can be a headache. (CSS has some different rules and won’t recognise certain characters.)

The attribute selector trick gets around those issues.:slight_smile:

1 Like

Thanks for this solution.

1 Like