0

I have the code to display the number of words of each post. This code I can from @Hektor in this post. Thanks Hektor..

But I have a new problem when applying it on my blog.

Here are the codes:

<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js' type='text/javascript'></script>

<div class="post">abc def ghi jkl mno pqr stu</div>
<div id="box"></div>
<div id="box"></div> //That this does not work

        <script>
            function wordcount(){

                    var e = $(".post");

                    var totalWords = 0;
                    for (var i = 0; i < e.length; i++) {

                        var innerTx = e[i].innerHTML;
                        var wordArray = innerTx.split(' ');
                        var thisTotal = wordArray.length;
                        totalWords += thisTotal;
                    }
                    if (totalWords > 15 ) {
                        $("#box").html("15+ words");
                    }
                        else if(totalWords > 10){
                        $("#box").html("10-15 words");
                        }
                        else if(totalWords > 5){
                        $("#box").html("5-10 words");
                        }
                        else if(totalWords > 0){
                        $("#box").html("0-5 words");
                        }
            }

            wordcount();
        </script>

If only placed one DIV, this works fine, but if for two div, it does not work.

There is a solution?

Community
  • 1
  • 1
Norax
  • 111
  • 7
  • 2
    That's because you can't have duplicate element `id`s – Sterling Archer Mar 01 '16 at 14:30
  • 2
    Possible duplicate of [Does duplicate id's screw up jquery selectors?](http://stackoverflow.com/questions/1053882/does-duplicate-ids-screw-up-jquery-selectors) – Marcos Pérez Gude Mar 01 '16 at 14:33
  • @Marcos Good, but it seems like a lot of difference in terms of questions and I have not found the answer of the page. Thank you.. – Norax Mar 01 '16 at 14:43
  • 1
    Isn't the answer obvious? The problem is that you have duplicate IDs. The solution is to simply not do that. – Lightness Races in Orbit Mar 01 '16 at 14:45
  • @Norax this site is full of questions about problems with duplicated ids in elements. Obviously it's not the exact solution for you, but is the exact problem that you have. Obvious thing: don't use duplicated ids. Change by properties or classnames.That's all. – Marcos Pérez Gude Mar 01 '16 at 14:48

1 Answers1

1

You can't use same id attributes for two different HTML tags You should use class selector instead of ID selection:

<div class="box"></div>
<div class="box"></div>

$(".box").html("... words");
kdureidy
  • 960
  • 9
  • 26