I have div elements that have an icon inside, and I want to use the find() method to return which of the 4 types of icons is inside. Is there a way to use find() with a regular expression to return the class?
EDIT: I’ve updated the divs to show how the <i>
is "buried" within the div and not a direct child
<div id="a" class="tile">
<span>
<span>
<i class="led-red"></i>
Led Red
</span>
</span>
</div>
<div id="b" class="tile">
<span>
<span>
<i class="led-green"></i>
Led Green
</span>
</span>
</div>
<div id="c" class="tile">
<span>
<span>
<i class="led-yellow"></i>
Led Yellow
</span>
</span>
</div>
var rexValues = /(led-green|led-yellow|led-red|led-null)/;
//this would work for element "a" if element "a" had the class attached,
//but because the class is buried inside I need to use find()
var aclass = a.className.match(rexValues);
//I'm looking to do something more like
var aclass = $(a).find(rexValues);
This is part of a sort function where I am sorting the divs based on their icon. The solution I’m basing off of is here: https://stackoverflow.com/a/46026203/9537489
2
Answers
Don’t use regex when not needed
I am using the sort order from your linked answer
container
can bedocument.body
if you do not have a static container near the tiles, but then the tiles will be moved if you have other stuff in the container. Let me know if you need to replace in placeI use the
[...nodeList]
spread syntax becausesort
is not a native method of a nodeList. NOTE: the spread has to be on the querySelectorAll statement or the tiles will not retain their sort orderthe
find
method in jQuery doesn’t support this. There is an extension that you could use to add this functionalityAre those classes with the prefix limited or unique? You could use the selector startsWith (
[<attr>^=<value>]
, i.e.[class^=led-]
). Here’s the CSS selector reference if you don’t want to add the jQuery based functionality