Shah Rushabh Shah Rushabh - 24 days ago 9
HTML Question

jQuery element is not removing

I want to remove element where

id=decoratives / Interior
but it not working.

If it is not working because special character then how can I change
/
with whitespace?



$(".remove").on("click", function(e) {
e.preventDefault();
var category = $(this).data("cat");
$('#' + category.replace(/\s/g, '')).remove();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="decoratives/Interior">
<a class="fancybox-gallery" href="http://wallpapercraze.com/images/wallpapers/nowallpaper-585747.jpeg">
<img class="animate scale animated" src="http://wallpapercraze.com/images/wallpapers/nowallpaper-585747.jpeg" alt="Image1" style="height:75px">
<div class="image-hover">
<i class="icon-zoom-in-2"></i>
</div>
</a>
<br>
<a class="remove" data-cat="decoratives / Interior">Remove Image</a>

</div>




Answer

Use attribute equals selector since itcotains meta-character /.

$('[id="' + category.replace(/\s/g,'') + '"]').remove();

$(".remove").on("click", function(e) {
  e.preventDefault();
  var category = $(this).data("cat");
  $('[id="' + category.replace(/\s/g, '') + '"]').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="decoratives/Interior">
  <a class="fancybox-gallery" href="http://wallpapercraze.com/images/wallpapers/nowallpaper-585747.jpeg">
    <img class="animate scale animated" src="http://wallpapercraze.com/images/wallpapers/nowallpaper-585747.jpeg" alt="Image1" style="height:75px">
    <div class="image-hover">
      <i class="icon-zoom-in-2"></i>
    </div>
  </a>
  <br>
  <a class="remove" data-cat="decoratives / Interior">Remove Image</a> 

</div>


or you need to escape meta-character / by \\/.

$('#' + category.replace(/\s/g,'').replace('/','\\/')).remove();

$(".remove").on("click", function(e) {
  e.preventDefault();
  var category = $(this).data("cat");
  $('#' + category.replace(/\s/g, '').replace('/', '\\/')).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="decoratives/Interior">
  <a class="fancybox-gallery" href="http://wallpapercraze.com/images/wallpapers/nowallpaper-585747.jpeg">
    <img class="animate scale animated" src="http://wallpapercraze.com/images/wallpapers/nowallpaper-585747.jpeg" alt="Image1" style="height:75px">
    <div class="image-hover">
      <i class="icon-zoom-in-2"></i>
    </div>
  </a>
  <br>
  <a class="remove" data-cat="decoratives / Interior">Remove Image</a> 

</div>

From jQuery Selectors docs :

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`` {|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").

Comments