Reputation: 1866
I have searched for some questions regarding this (like How to handle special characters in html element id/name in Jquery validation?), but unfortunately it doesn't help me, or I didn't undertsood the trick...
Let's say we have a button, with a class .bt
and the id my|id
. (or other special separators like ,:;|
)
It doesn't seem to be possible to use it to match another element like $('#other_'+$('.bt').attr('id'))
You can see an example here.
So my question, is how to transmit those specials characters (,:;|
) ?
Upvotes: 0
Views: 248
Reputation: 50905
Here's an example that still uses the id
selector, but also allows for any special characters you want to be able to use:
$(document).ready(function () {
$(".bt").on("click", function () {
var escaped = $(this).attr("id").replace(/([,:;|])/g, "\\$1");
console.log("escaped: " + escaped);
$("#other_" + escaped).toggleClass("testing");
});
});
Upvotes: 1
Reputation: 121
This is a deviation from pure-jQuery solutions, but maybe in this case it's better to use native document.getElementById(...)
function?
$(document.getElementById('other_' + $('.bt').attr('id')))
It reads a bit more verbose, but seems more clear/consistent/safe than mucking about with regexes.
Upvotes: 2
Reputation: 1174
Like this?
$('#other_' + $('.bt').attr('id').replace('|', '\\|'));
Upvotes: 1
Reputation: 6366
This worked:
$('[id="div_' + id + '"]').html(id);
instead of this:
$('#div_'+id).html(id);
Fiddle here
-Edit-
New fiddle that shows usage of ,:;|
Upvotes: 2