1

This is a follow-up query for How to get the total instance of the :contains() Selector

I have this array loop issue on getting the total match using contains:selector...

Here are my variables -

var filterarray = ["Content1", "goes"];

<div id="content" style="display:none">Content1 goes here</div>
<div id="content" style="display:none">Content1 goes here too</div>
<div id="content" style="display:none">Content1 goes here again</div>
<div id="content" style="display:none">extra node</div>

Here's my script -

totalSum = 0;
for (i=0;i<filterarray.length;i++){ 
        $( "div[id^=content]:contains('"+ filterarray[i] +"')").css( "display", "block" );      
        totalSum += $( "div[id^=content]:contains('"+ filterarray[i] +"')").length;      
    }

$("#results").append("Total Results: " +totalSum);

The results shows = 6, wherein it should only be 3 because the div is already in "block". I think the count goes for each "Content1" = 3 and "goes" = 3, total of 6.

QUESTION: Is there a way to show only 3 and ignore if there are multiple matches (or duplicates) within a DIV instance?

Community
  • 1
  • 1
syntaxcode
  • 133
  • 2
  • 16

2 Answers2

1

This might help you: http://api.jquery.com/jquery.unique/

http://jsfiddle.net/xb14h1ev/1/

HTML:

<div class="content" style="display:none">Content1 goes here</div>
<div class="content" style="display:none">Content1 goes here too</div>
<div class="content" style="display:none">Content1 goes here again</div>
<div class="content" style="display:none">extra node</div>

<div id="results"></div>

JS:

var filterarray = ["Content1", "goes"];
$(function(){
    totalSum = 0;
    var divs = [];
    for (i=0;i<filterarray.length;i++){ 
        $( "div.content:contains('"+ filterarray[i] +"')").css( "display", "block" );
        $.merge(divs, $( "div.content:contains('"+ filterarray[i] +"')"));
    }
    totalSum = $.unique(divs).length;
    $("#results").append("Total Results: " +totalSum);
});
Zentoaku
  • 766
  • 4
  • 12
1

First advice use classes instead of ids! Because id means UNICAL IDENTIFICATOR. Read about this note.

So assume you have next html nodes

<div class="content" style="display:none">Content1 goes here</div>
<div class="content" style="display:none">Content1 goes here too</div>
<div class="content" style="display:none">Content1 goes here again</div>
<div class="content" style="display:none">extra node</div>

Iterate all nodes with content class.

var nodes = $(".content");
var filterarray = ["Content1", "goes"];
var total = 0;

for(var i = 0; i < nodes.length; i++){
    var current = $(nodes[i]);
    var text = current.text();
    var res = filterarray.reduce(function(p, a){
        return p && (text.indexOf(a) != -1);
    }, true);
    if(res) total++;
}

console.log(total)

Demo

Community
  • 1
  • 1
Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37