JQuery selector cointains parentheses

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();

Answers:

Answer

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();
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.