Reputation: 11
I have a problem with the character "+" inside a string passed to jQuery object $()
I tried to initialize String object and concat but the problem remains the same.
function fn(string){
$(string).show();
}
let myString = ".my-class-that-contains+";
fn(myString);
The code doesn't response as expected. When i remove the character "+" from the end of the string all works fine.
Upvotes: 0
Views: 77
Reputation: 547
you can use like selector for it.
function fn(string){
// $(string).show();
$('[class="'+string+'"]').show();
}
let myString = ".my-class-that-contains+";
fn(myString);
For reference: https://api.jquery.com/attribute-starts-with-selector/
Upvotes: 0
Reputation: 943142
+
has a defined meaning in a selector. It is a sibling combinator.
To use it in a class name in a class selector, you need to escape it (with a \
).
Remember that the CSS escape character is also the JavaScript escape character so you have to escape the \
characters in the selector to put them in the JavaScript string literal.
function fn(string){
$(string).show();
}
let myString = ".my-class-that-contains\\+";
fn(myString);
div { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my-class-that-contains+">
This is hidden by default
</div>
It is best to avoid using special characters in class names in the first place.
Upvotes: 1