-2

Initial state is that I have an array of ids [45, 3, 678] and a div tag with lots of elements inside, they are nested and all of them have a unique ids. I need to add class "selected" only for those elements, whose ids are in the array of ids. How can I achieva that?

<div id="parent-class">
  <details id=1>
    <ul id=2>
      <details id=3></details>
      <details id=4></details>
      <details id=5></details>
      ...
    </ul>
  </details>
  <details id=56>
    <ul id=57>
      <details id=58></details>
      <details id=59></details>
      <details id=60></details>
      ...
    </ul>
  </details>

</div>



$('div#parent-class').ready(function () {
    var options = [45, 3, 678];

    /* Here I need to loop through all children and assign class for those elements whose id is in array options*/
    $('div#parent-class').children().each(function(){
      var id = $(this).attr('id');
      if ($.inArray(id, options)) $(this).addClass('selected');
    });
  });

Any help is very appreciated

koal
  • 69
  • 6
  • 2
    You can't use numerics for `id=` you might want `data-id=` instead: https://stackoverflow.com/a/79022/2181514 – freedomn-m Jul 10 '19 at 07:49
  • What have you tried so far? Do you know how to create `for` loop? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for – freedomn-m Jul 10 '19 at 07:50
  • "*.children() only travels a single level down the DOM tree*" https://api.jquery.com/children/ change to `$("div#parent-class").find("*").each...` – freedomn-m Jul 10 '19 at 08:02
  • 1
    Side note, in case it matters: `
    ` is not supported in IE (all versions) and Edge (upto v18). See here: https://www.caniuse.com/#search=details
    – Peter B Jul 10 '19 at 08:04

1 Answers1

0

As @freedomn-m commented out you need your ids to contain at least one alpha caracter so i suggest you change your ids, for the loop you simply use the attribute selector to select the elements in your array

$('div#parent-class').ready(function () {
    var options = [56, 3, 60];
    options.forEach(function(v,i) {
      $('[id="item_'+v+'"]').addClass('selected');
      //or $("#item_" + v).addClass('selected');
    })
  });
.selected{border:1px solid red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent-class">
  <details id="item_1">
    <ul id="item_2">
      <details id="item_3"></details>
      <details id="item_4"></details>
      <details id="item_5"></details>
      ...
    </ul>
  </details>
  <details id="item_56">
    <ul id="item_57">
      <details id="item_58"></details>
      <details id="item_59"></details>
      <details id="item_60"></details>
      ...
    </ul>
  </details>

</div>
madalinivascu
  • 32,064
  • 4
  • 39
  • 55