Venkat
Venkat

Reputation: 2186

find other attributes of a class name in a element

I have the following piece of code:

<div class="_GAb-_GAd">
    <div class="_GANmb _GAe ACTION-removeFilter TARGET-1">clear</div>
</div>

<div class="_GAb-_GAd">
    <div class="_GANmb _GAe ACTION-removeFilter TARGET-2">clear</div>
</div>

and the script (Jquery)

<script>
    $(document).ready(function() {
        $(".ACTION-removeFilter").click(function() {
            alert('find out which TARGET is being clicked.');
        });
    });
</script>

I want to know which TARGET is being clicked (TARGET-1 or TARGET-2). Is there a way to find out?

How will I know it?

Upvotes: 2

Views: 33

Answers (1)

Tushar
Tushar

Reputation: 87203

You can use regex on className

var target = $(this).attr('class').match(/\b(TARGET-[^ ]+)/)[1];

Regex Demo and Explanation

  1. \b: Word Boundary
  2. (): Capturing Group. Can be accessed by using second index(1) of array
  3. TARGET-: Matches TARGET- literally
  4. [^ ]*: ^: Not. Matches anything that is not space, zero or more times.

Note: To match case-insensitively use i flag. I assumed that there will always be something after - so used +.

Demo:

$(document).ready(function() {
  $(".ACTION-removeFilter").click(function() {
    console.log($(this).attr('class').match(/\b(TARGET-[^ ]+)/)[1]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="_GAb-_GAd">
  <div class="_GANmb _GAe ACTION-removeFilter TARGET-1">clear</div>
</div>

<div class="_GAb-_GAd">
  <div class="_GANmb _GAe ACTION-removeFilter TARGET-2">clear</div>
</div>

<div class="_GAb-_GAd">
  <div class="_GANmb _GAe ACTION-removeFilter TARGET-My_Beautiful_class_488">Check this</div>
</div>

Upvotes: 5

Related Questions