如果元素具有相同的属性值,则从元素中消除元素

时间:2018-02-09 10:26:40

标签: jquery arrays

我为这个数组获取了这样的元素:

var headerElements = document.getElementsByClassName("headerElement");

我喜欢消除数组中具有相同属性的元素" title",如下所示:

  $.each(headerElements, function(i, el){
    el.attr('title') is already in the array, remove the element from the array
});

但我不知道该怎么办。如果有人有建议,我将非常感激。

1 个答案:

答案 0 :(得分:0)

您可以遍历您的元素并将title属性存储在Array中。如果已存储title属性,请从Array

中删除该元素

var selected = $('.common');
console.log('The array contains '+selected.length+' elements before any modification.');

var titleList = [];
$('.common').each(function(){
  if(!titleList.includes($(this).attr('title'))) titleList.push($(this).attr('title'));
  else selected = selected.not($(this));
});

console.log('The final array contains '+selected.length+' elements.');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="common" title="1"></div>
<div class="common" title="1"></div>
<div class="common" title="2"></div>
<div class="common" title="2"></div>
<div class="common" title="3"></div>
<div class="common" title="3"></div>