1

i have a html button, like below. it will have a attribute

<button class="first-button" data-content='{8C2E25C4-5E4F-484C-97D0-F42305F30E19}'> my content</button>

on click of this button i need to get that attribute and make a attribute selector out of it, for another element with a different class and same attribute

<button class="second-button" data-content='{8C2E25C4-5E4F-484C-97D0-F42305F30E19}'> my content</button>

i tried jquery attribute selector and that didn't work

$('data-content=8C2E25C4-5E4F-484C-97D0-F42305F30E19')

i am open to a JS or jQuery fix

Amit Pandey
  • 274
  • 4
  • 16
  • Why was this re-opened? It's a very common duplicate. – Rory McCrossan Mar 09 '21 at 13:04
  • @RoryMcCrossan The dupe was how to select a data attribute, not how to select a data attribute with special characters. Also I had an answer which was more up to date than the dupes I could find – mplungjan Mar 09 '21 at 13:26
  • There aren't special characters if you simply wrap the value in quotes, which is what the solution in the dupe explained. *Edit* - and @Swati's answer below does. – Rory McCrossan Mar 09 '21 at 13:45

3 Answers3

2

You can try like below :

$('button[data-content="{8C2E25C4-5E4F-484C-97D0-F42305F30E19}"]').addClass("active")
.active {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="first-button" data-content='{8C2E25C4-5E4F-484C-97D0-F42305F30E19}'> my content</button>

<button class="second-button" data-content='{8C2E25C4-5E4F-484C-97D0-F42305F30E19}'> my content</button>
Swati
  • 28,069
  • 4
  • 21
  • 41
0

You need [] for attribute selectors and will need a wildcard operator in selector since the value has {}

$('[data-content*=8C2E25C4-5E4F-484C-97D0-F42305F30E19]').css('color','red')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="first-button" data-content='{8C2E25C4-5E4F-484C-97D0-F42305F30E19}'> my content</button>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Alternative to quotes is jQuery.escapeSelector or CSS.escape

const data = CSS.escape("{8C2E25C4-5E4F-484C-97D0-F42305F30E19}")
$(`button[data-content=${data}]`).addClass("active")
.active {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="first-button" data-content='{8C2E25C4-5E4F-484C-97D0-F42305F30E19}'> my content</button>

<button class="second-button" data-content='{8C2E25C4-5E4F-484C-97D0-F42305F30E19}'> my content</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236