Reputation: 2186
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
Reputation: 87203
You can use regex
on className
var target = $(this).attr('class').match(/\b(TARGET-[^ ]+)/)[1];
\b
: Word Boundary()
: Capturing Group. Can be accessed by using second index(1) of arrayTARGET-
: Matches TARGET-
literally[^ ]*
: ^
: 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