-1

I want to have a javascript code that counts how many times the text "Apple" appears in the current document (let this number be N) and creates a new div in whic it adds the aforementioned text N times.

So far I've managed to count how many times 'Apple' appears in the document using an example found on the internet, like this:

JS

window.getCount = function(parent, getChildrensChildren){
    var relevantChildren = 0;
    var children = parent.childNodes.length;
    for(var i=0; i < children; i++){
        if(parent.childNodes[i].nodeType != 3){
            if(getChildrensChildren)
                relevantChildren += getCount(parent.childNodes[i],true);
            relevantChildren++;
        }
    }
    return relevantChildren;
}

HTML

<pre>
<div id="test">
    <span>Apple</span>
    <span>Apple.</span>
    <span>Apple</span>
    <span>Apple</span>
    <span>Apple</span>
    <span>Apple</span>
</div>
<pre>
<a href="#" onclick="alert(getCount(document.getElementById('test'), false));">Show counter:</a>

Thank you.

Liam
  • 27,717
  • 28
  • 128
  • 190
SimpleFuzz
  • 69
  • 9

1 Answers1

0

try this

<pre>
<div id="test">
    <span>Apple</span>
    <span>Apple.</span>
    <span>Apple</span>
    <span>Apple</span>
    <span>Apple</span>
    <span>Apple</span>
</div>
<pre>
<a href="#" onclick="alert(getCount(document.getElementById('test'), false));">Show counter:</a>
<div class="response">

</div>


window.getCount = function(parent, getChildrensChildren){
        var relevantChildren = 0;
        var children = parent.childNodes.length;
        for(var i=0; i < children; i++){
            if(parent.childNodes[i].nodeType != 3){
                if(getChildrensChildren)
                    relevantChildren += getCount(parent.childNodes[i],true);
                relevantChildren++;
            }
        }
            document.body.getElementsByTagName('div')[1].innerHTML  = relevantChildren;
        return relevantChildren;
    }