0

I have randomly generated classes in my HTML file. class="page-index-1, class="page-index-2, class="page-index-3, etc. I need get these classes using only the prefix page-index-and with this get all the classes. I tried to use JQuery $('div[class*=page-index-]').find(); this gives me a huge object but I can't find the classes inside of this.

Does someone have any idea about how can I get these classes? I need to get to reorder as I need it.

W.GTR
  • 3
  • 4
  • 1
    Incremental class/id attributes are generally a bad idea for the exact reason you're describing. Give all the elements the same class and the problem goes away and your code quality improves. – Rory McCrossan Nov 06 '20 at 13:33
  • 1
    As above with the added info to add the `-1` `-2` etc parts as `data-` attributes, eg `
    2
    `
    – freedomn-m Nov 06 '20 at 13:34
  • Please include the code you've used. `$(selector).find()` will return 0 elements - so if it's a "huge object" you're probably looking at the empty jquery collection. Check with `.length`, eg `$('div[class*=page-index-]').find().length === 0)` - in your case you want just `$('div[class*=page-index-]')` - without the `.find()` as `.find()` says "get child items that match null" (which is nothing) – freedomn-m Nov 06 '20 at 13:37
  • 1
    You can use the CSS starts with selector: JQuery: `$('[class^="page-index-"]')` Vanilla: `document.querySelectorAll('[class^="page-index-"]')`. As freedomn said, using .find() will get you all child elements. – EJTH Nov 06 '20 at 13:39
  • 2
    Does this answer your question? [jQuery: Finding partial class name](https://stackoverflow.com/questions/33615334/jquery-finding-partial-class-name) – freedomn-m Nov 06 '20 at 13:39

1 Answers1

0

Please, try this:

const list = []
$('[class]').each(function() {
  this.classList.forEach(function(className) {
    if (!className.indexOf('page-index-')) {
      list.push(className)
    }
  })
})
console.log(list) //list contains generated class
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page-index-1"></div>
<div class="page-in"></div>
<div class="page-index-2"></div>
<div class="page-index-3"></div>
Nel
  • 454
  • 5
  • 14