Francesco G. Francesco G. - 10 months ago 147
jQuery Question

jQuery check if exist in array an html element

I would to have an array with html element, but I don't want have duplicate.
Is possible that $.inArray() don't work with html element?



var rowsArr= new Array();
var rowMst=$('.a');

rowsArr.push(rowMst[0]);

if($.inArray(rowsArr, rowMst[0]) === -1) {
rowsArr.push(rowMst[0]);
}else{
alert("Already exist");
}

console.dir(rowsArr);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="a">Hello</div>
<div class="b">Stack</div>
<div class="c">Overflow</div>




Answer Source

Yes,inArray will work. Minor issue in your code at line number 4 corrected here. $.inArray(value, array, index)

var rowsArr= new Array();
var rowMst=$('.a');

rowsArr.push(rowMst[0]);

if($.inArray(rowMst[0],rowsArr) === -1) { 
  rowsArr.push(rowMst[0]); 
}else{
  alert("Already exist");
}

console.dir(rowsArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="a">Hello</div>
<div class="b">Stack</div>
<div class="c">Overflow</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download