How would you store the remaining part of a class selector as a variable for a foreach loop

for example:

<div class="sel_child1">something</div>
<div class="sel_child2">something</div>

i know i can sect with:

jQuery( "[class^='sel_']" )

but i need the remainder for the foreach loop because the second part of the class is the child element to target and before you ask i know i should use a data attribute or another method but the CMS i am using wont let me.

it is also possible that the div has additional unrelated classes.

1 Answers

3
Tyler Roper On Best Solutions

You could get the entire string of classes using the .attr("class") method. From there it's a matter of breaking it into a list of classes, finding the one that starts with "sel_", and storing the second piece.

$("[class*='sel_']").each(function() {     //match all classes with sel_ in them
  const child = $(this)         
    .attr("class")                         //get the class string
    .split(" ")                            //break it into individual classes
    .find(n => n.startsWith("sel_"))       //find the one that starts with sel_
    .split("_")[1];                        //split it on _ and take the second piece

  console.log(child);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sel_child1 unrelated">something</div>
<div class="unrelated sel_child2">something</div>

And a more concise RegEx alternative...

$("[class*='sel_']").each(function() {
  const child = $(this).attr("class").match(/(?:^|\s)sel_([^\s]*)/)[1];
  console.log(child);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sel_child1 unrelated">something</div>
<div class="unrelated sel_child2 xsel_child3">something</div>


RegEx Reference

(?:^|\s) - start of string or a space (non-capture)

sel_ - "sel_"

([^\s]*) - everything until the next space (capture)