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
  • 1,081
  • 1
  • 13
  • 25
hretic
  • 999
  • 9
  • 36
  • 78

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,867
  • 3
  • 42
  • 60
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
  • 7,873
  • 1
  • 20
  • 44
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
  • 24,551
  • 7
  • 52
  • 62
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
  • 10,771
  • 1
  • 21
  • 40