1

Imagine that we have this HTML structure:

<main>
   <div id="one"></div>
   <div data-type="John 'phil',15">Light</div>
</main>

I would like to select the element using its data-type however when I try my code gives me an error:

let aliasScape = alias.replace(/['.*+?^${}()|[\]\\]/g, '\\$&'); //alias is "John 'phil',15"
$("[data-type =| '" + aliasScape + "']")

expression not recognized [data-type =| 'John 'phil',15']

Does anyone know what is wrong? Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Apol0x
  • 21
  • 4
  • Possible duplicate of [Escaping double quotes in CSS selector](https://stackoverflow.com/questions/25443917/escaping-double-quotes-in-css-selector) – Heretic Monkey Oct 01 '19 at 14:28
  • 2
    You can also use [`jQuery.escapeSelector()`](https://api.jquery.com/jQuery.escapeSelector/) – billyonecan Oct 01 '19 at 14:32
  • Sorry for delay. Exactly, finally I used the $.scapeSelector() it was more clear to other teammates and the propouse, thanks for the interest ;) – Apol0x Oct 04 '19 at 22:19

2 Answers2

0

To simplify the selector you can provide a function to filter() which matches directly using the data() method. This way you don't need to mess around escaping the value to work in a selector:

let alias = "John 'phil',15";
var $elements = $("[data-type]").filter(function() {
  return $(this).data('type') == alias;
});

console.log($elements.length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main>
   <div id="one"></div>
   <div data-type="John 'phil',15">Light</div>
</main>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Try enclosing selector with single quotes and |= instead of =|

let alias = "John 'phil',15"
console.log($('[data-type|="' + alias + '"]')[0])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main>
   <div id="one"></div>
   <div data-type="John 'phil',15">Light</div>
</main>
User863
  • 19,346
  • 2
  • 17
  • 41