Dennis
Dennis

Reputation: 538

Iterate in list and get nearest values

How can I loop in the list below and set the values of the as a class on the input? But it cannot iterate over the .liBrand list item.

<ul>
    <li class="liModelFilter liMultipleSelectionFilter">
        <ul>
             <li class="liBrand"><b>Mini</b></li>
             <li>
                 <input type="checkbox" value="1090" id="ModelIds">
                 <span>Cooper</span>
             </li>
             <li>
                 <input type="checkbox" value="1092" id="ModelIds">
                 <span>One</span>
             </li>
        </ul>
    </li>
 </ul>

Required result:

<li>
    <input class="Cooper" type="checkbox" value="1090" id="ModelIds">
    <span>Cooper</span>
</li>

I need this because I have to create a custom checkbox - each checkbox has to have to logo of the type (Cooper, One,...).

I already tried something like this:

jQuery($('.liModelFilter ul li:not(.liBrand)')).each(function() {
    console.log($('.liModelFilter ul li:not(.liBrand)')).html();
});

Upvotes: 1

Views: 30

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

The simplest way to do this would be to call addClass() on the input elements, and provide a function which returns the text content of the sibling span, something like this:

$('.liModelFilter :checkbox').addClass(function() {
  return $(this).next('span').text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="liModelFilter liMultipleSelectionFilter">
    <ul>
      <li class="liBrand"><b>Mini</b></li>
      <li>
        <input type="checkbox" value="1090" class="ModelIds">
        <span>Cooper</span>
      </li>
      <li>
        <input type="checkbox" value="1092" class="ModelIds">
        <span>One</span>
      </li>
    </ul>
  </li>
</ul>

Also note that I changed the id="ModelIds" to a class, as you cannot have duplicate id attributes within the DOM.

Upvotes: 1

Related Questions