Home > Blockchain >  how to get the first of each different class in div
how to get the first of each different class in div

Time:12-17

How can i get the first instance of each div class within same div

example

<div id="wrap">
    <div >GET THIS</div>
    <div ></div>
    <div >GET THIS</div>
    <div >GET THIS</div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
</div>

tried

$('div[div*="class_"]:first').each(function(){
       //do something
});

CodePudding user response:

I don't think there's a built-in way to do that, but it's easy enough to iterate over all divs in reverse order and put them into a collection indexed by class. No need for a big library like jQuery for something this trivial:

const divs = document.querySelectorAll('#wrap > div');
const divsByClass = {};
for (const div of [...divs].reverse()) {
  divsByClass[div.className] = div;
}
for (const div of Object.values(divsByClass)) {
  console.log(div);
}
<div id="wrap">
    <div >GET THIS</div>
    <div ></div>
    <div >GET THIS</div>
    <div >GET THIS</div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
</div>

If you really had to use jQuery as well, it wouldn't help the syntax much.

const divsByClass = {};
for (const div of $('#wrap > div').get().reverse())  {
  divsByClass[div.className] = div;
}
for (const div of Object.values(divsByClass)) {
  console.log(div);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrap">
    <div >GET THIS</div>
    <div ></div>
    <div >GET THIS</div>
    <div >GET THIS</div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
</div>

  • Related