2

I'm trying to select the element with class="{c}"

<div id="main">
    <div class="{c}">  some data </div>
    <div class="{c}">  some data </div>
    <div class="{c}">  some data </div>
    <div class="{c}">  some data </div>
</div>

here is my jQuery code :

$('#main').find('.{c}' ).each(function()
{
    console.log($(this).html());
})

but i get error:

Uncaught Error: Syntax error, unrecognized expression: .{c}

how can i select this element ?

btw , I'm scraping data from some website using chrome puppeteer ... i don't own the website and can't change the class name

AmirBll
  • 935
  • 1
  • 8
  • 23
hretic
  • 1,201
  • 4
  • 24
  • 55

4 Answers4

6

You can escape the curly braces using two backslashes:

$(".\\{c\\}")

As per the documentation:

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

So using your example:

$('#main').find('.\\{c\\}' ).each(function()
{
    console.log($(this).html());
})

Example fiddle: https://jsfiddle.net/83tcg7fb/

Brett Gregson
  • 5,652
  • 3
  • 39
  • 57
2

Despite { and } being invalid characters for classes, you can use the attribute selector (specifically ^= for prefix) considering you can't change the HTML

$('#main').find('[class^="{c"]').each(function() {
  console.log($(this).html());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
  <div class="{c}"> some data </div>
  <div class="{c}"> some data </div>
  <div class="{c}"> some data </div>
  <div class="{c}"> some data </div>
</div>
chazsolo
  • 6,692
  • 1
  • 15
  • 38
1

You can use $.escapeSelector( "{c}" )

$('#main').find( "." + $.escapeSelector( "{c}" ) ).each(function()
{
    console.log($(this).html());
})

$('#main').find( "." + $.escapeSelector( "{c}" ) ).each(function()
{
    console.log($(this).html());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
    <div class="{c}">  some data </div>
    <div class="{c}">  some data </div>
    <div class="{c}">  some data </div>
    <div class="{c}">  some data </div>
</div>
Hien Nguyen
  • 21,001
  • 7
  • 35
  • 48
1

To achieve expected result, use contains selector (*)

https://api.jquery.com/attribute-contains-selector/

$('#main').children('div[class*=c]').each(function(){
    console.log($(this).html());
})
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

 <div id="main">
    <div class="{c}">  some data </div>
    <div class="{c}">  some data </div>
    <div class="{c}">  some data </div>
    <div class="{c}">  some data </div>
</div>

codepen - https://codepen.io/nagasai/pen/arzBYm

Naga Sai A
  • 9,949
  • 1
  • 15
  • 34