How to remove only duplicate ul items for each li item using javascript html
P粉418214279
P粉418214279 2024-03-29 20:54:12
0
1
392

I display a dynamically generated navigation structure. Each location has a store type generated from that location's stores.

I need to remove duplicates for each location so groceries can appear in both locations. I tried the common jquery solution below which removes duplicates but it results in each storetype appearing in only one location.

var seen = {};
$("ul#storetypes").find("li").each(function(index, html_obj) {
  txt = $(this).text().toLowerCase();

  if (seen[txt]) {
    $(this).remove();
  } else {
    seen[txt] = true;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
  <li>Location 1
    <ul id="storetypes" class="sub-menu">
      <li>groceries</li>
      <li>cakes</li>
      <li>motor spares</li>
      <li>groceries</li>
    </ul>
  </li>
  <li>Location 2
    <ul class="sub-menu">
      <li>groceries</li>
      <li>motor spares</li>
      <li>motor spares</li>
      <li>groceries</li>
    </ul>
  </li>
</ul>

P粉418214279
P粉418214279

reply all(1)
P粉432906880

You can do this:

$("ul.sub-menu li").each(function(index, html_obj) {
  if ($(this).prevAll(":contains(" + $(this).text() + ")").length > 0) {
    $(this).remove();
  }
});

This will look at each .sub-menu and see if there is a "li" with the same text, and remove the duplicates.

Demo

$("ul.sub-menu li").each(function(index, html_obj) {
  if ($(this).prevAll(":contains(" + $(this).text() + ")").length > 0) {
    $(this).remove();
  }
});
sssccc
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!