4

I have div's with ids that are pulled from a database. These ids sometimes contain parentheses and this causes the JQuery selector to not work. What can I do?

Here is an example of what I am talking about:

https://jsfiddle.net/2uL7s3ts/1/

var element = 'hello (world)';
$('#' + element).hide();
Matthew Morris
  • 323
  • 2
  • 7

2 Answers2

1

You can use the attribute selector for ID

$("[id='" + element + "']").hide();

or modify your string selector with a regex to remove the parentheses and spaces

element = element.replace(/(?=[() ])/g, '\\');
$('#' + element).hide();
Community
  • 1
  • 1
Andrew Brooke
  • 12,073
  • 8
  • 39
  • 55
1

Rather than using an attribute selector, as the other answer suggests, I would suggest switching back to the native getElementById method.

$(document.getElementById(element)).hide();

The reason I sugguest this over an attribute selector is for performance reasons. An attribute can exist on any element, so when you perform it, javascript has to scan every element within the context to see if it has the attribute with a matching value.

Using getElementById, which takes a literal id and not a selector, the DOM scan will not happen.

Taplar
  • 24,788
  • 4
  • 22
  • 35