Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find element having an email address as class name using jQuery?

How can I find an element having an email address as class name. Email address is dynamic.

$(document).ready(function(){
  //not working getting error
  var email="[email protected]";
  $("#main").find("."+email);
  //not working
  $("#main").find("."+escapeSelecorchars(email));
});

function escapeSelecorchars = function(val) {
  return val.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g,"\\\\$&");
};
<div id="main">
  <div class="[email protected]"></div>
</div>
like image 882
pareshm Avatar asked Mar 11 '23 23:03

pareshm


2 Answers

I'd try something like this

Js:

$(function() {
  var email = "[email protected]";
  var div = $("#main").find("div[data-email='"+email+"']");
});

Html:

<div id="main">
  <div data-email="[email protected]"></div>
</div>

Here is a working plunker https://plnkr.co/edit/BDo9SvksNIfCLa6I0HfI

like image 94
michalh Avatar answered Mar 13 '23 13:03

michalh


I agree that it's probably not the best idea to use an email address as a class. However, the only reason your escaping approach doesn't work is because you are escaping incorrectly. You have too many \ in your replacement value.

It should be

function escapeSelecorchars(val) {
  return val.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g,"\\$&");
};

and then it works.

like image 31
Felix Kling Avatar answered Mar 13 '23 12:03

Felix Kling