0

I have this code:

var imgId = this.id; //file1.jpg

and this:

$('.img\\' + imgId).remove();

So the problem is, i cant escape the '.' because its in the var, not before. What can i do?

benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • Your class is `.imgfile1.jpg`? – Shef Sep 12 '11 at 16:08
  • You have a `class` that contains the filename? Why? The `src` already contains the filename… – Tomalak Sep 12 '11 at 16:11
  • moreover the selector `'.img\file1.jpg'` will be interpreted as class `'img\file1'` and class `'jpg'`, ie class `'img\file1 jpg'`. "." (dot) is a class selector, ans should be escaped in ids or classes (as "#" and other "selectors" characters – roselan Sep 12 '11 at 16:38

5 Answers5

4

Don't store the filename as part of the class/id in your markup. Instead, use a data- attribute:

<div class="img" data-filename="file1.jpg" />

And then in your jQuery:

$('.img[data-filename="'+imgId+'"]').remove();
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • The `src` already contains the filename. Storing it anywhere else is redundant at best. – Tomalak Sep 12 '11 at 16:12
  • @Tomalak - Assuming you're working with an img element, yes. That's never specified in the post though. Could easily be working with an input/div/etc. related to an image (but not containing the image itself). – Justin Niessner Sep 12 '11 at 16:13
  • @Justin: Uhm, right. Could be. I would still do something like `$(".img[src$='"+filename+"']").closest("div.container").remove()` in such a case. – Tomalak Sep 12 '11 at 16:20
0

I've probably misunderstood the question - but, would this work?

$('.img\\' + replace(imgId,'.','\.')).remove();
ipr101
  • 24,096
  • 8
  • 59
  • 61
0

can't you do something like $("#"+imgId, ".img").remove()

cpjolicoeur
  • 12,766
  • 7
  • 48
  • 59
0

Use .replace to replace it.

var imgId = this.id.replace('.', '/.'); //Or whatever other escaping is there.
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

While the period is a valid entity in an HTML Id I strongly sugest you follow a different naming convention, specifically one where periods are not used in Id values.

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162