Count Number Of Div's By A Class Name

free web hosting
Open Discussion > CONTRIBUTE > Computers > Programming Languages > Java, Java Servlets, Java Script, & JSP

Count Number Of Div's By A Class Name

sonesay
I have a situation where I need to be able to count the number of div elements in a page and then use that number for a loop.

I've already tried this but it returns all child div elements.
CODE
ocument.getElementById("char_list").getElementsByTagName("div").length;

I need only the child nodes directly below the parent div 'char_list'.


THe structure is like this
CODE
<div id='char_list'>
<div class='char_node'></div>
<div class='char_node'></div>
<div class='char_node'></div>
</div>


The problem here is I also have nested div's inside the 'char_node' divs so the first code returns them all. I'm trying to just gather the char_node class divs and use it in my loop/function.

Reply

truefusion
CODE
function countElementsByClass(className, elementTag){
var count = new Array();
var elements = document.getElementsByTagName(elementTag);
for (var i = 0; i < elements.length; i++){
if (elements[i].className == className){
count[i] = "";
}
}
return count.length;
}

I put this together, i believe it'll get you what you want. Try it out and see if it is sufficient.

Reply

sonesay
CODE
function countElementsByClass(className, elementTag){
var count = new Array();
var elements = document.getElementsByTagName(elementTag);
for (var i = 0; i < elements.length; i++){
if (elements[i].className == className){
count[i] = "";
alert('found one!');
}
}
return count.length;
}

count = setTimeout("countElementsByClass('char_node', 'div');", 5000);
setTimeout('alert(count);',10000);



Thanks for that code Truefusion, I'm not sure what exactly is happening but I always seem to get a return of 5 on 'count', I change the two paramters being passed to that function but it still returns 5 which is weird because I put in an alert in that loop and it does alert the correct number of tagElement + className combination.

I'm sure this code will come in handy but I think I need to rethink a new approach to my problem, I've got a tab contents style section I am trying to build for each character profile. The problem is the tab contents example I got off dynamic drive http://www.dynamicdrive.com/dynamicindex17/tabcontent.htm is only for a single collection of tabs. I need to modify it to work for multiple number of character profiles. I guess this is kinda going off topic but thats the reason I wanted to get the divs with the certain class names. I think I should post another topic on it to futher explain my problem and hopefully get some more assistance on how to go about doing it.

 

 

 


Reply

gogoily
Try this one:
CODE
var count = 0;
var o = document.getElementById("char_list").getElementsByTagName("div");
for(var i=0;i<o.length;i+){
    if(o[i].className == "char_node")
        count ++;
}
alert(count);//You get your Div number here;)

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Recent Queries:-
  1. count number of div firefox - 291.20 hr back. (1)
  2. how to count number of inputs in a div - 453.50 hr back. (1)
  3. count number of lines in a div - 628.41 hr back. (1)
Similar Topics

Keywords : count, number, divs, class

  1. Battle For Middle Earth
    Uncomplicated RTS with class... (0)
  2. Constant Interface Or Constant Class?
    (1)
    I always use classes to hold constants instead of interfaces. Recently my co-worker started using
    Interface to hold constants for the same project. I think it's good to share with him some
    points of view from the following books which justify why should you avoid 'Constant
    Interface': Philip Heller and Simon Roberts, "Complete Java 2 Certification Study Guide": "In
    the first place, to say that a class implements an interface really means that the class exposes the
    public methods listed in the interface. Interfaces are for defining types and should be used ....
  3. Get Pan Number Online
    (0)
    Hi People This information is specific to India. So if you are from some other country , please read
    this only for information. I am sure everyone will need a PAN at some point of time... Now that its
    become online, applying and getting is very Easy. PAN(Permanent Account Number) (Related to Income
    TAX) can be applied online also and the process is very simple.It will take 15 days when you follow
    ordinary procedure and 5 days if you apply online. /wink.gif" style="vertical-align:middle"
    emoid=";)" border="0" alt="wink.gif" /> Below is the PAN Details page: http://in....
  4. My Spy Suggestions For Team Fortress 2 Next Update S
    Spy is my favorite class and I think these suggestions own (10)
    I thought about this and I like it. You may disagree or agree or may like 1 or 2, but still read it
    and tell me what you think. Spy --- Sapper Replacement Electronic Canceler: -------------------
    At a limited distance away, you must look at the sentry, teleporter, or dispenser and you can use
    your electronic canceler. It will freeze the sentry, dispenser, or teleporter for an X amount of
    seconds (I suggest 10) and once it is over, the engineer's building unfreezes. Engineer can
    still repair Now valve can do whatever they want with this but, I like this: You c....
  5. Much Fun In Math Class
    (8)
    You're asking what? Well, let me explain. Today our teacher handed our recent Math Exams back
    to us, so we could go over our mistakes, etc. Well my friend (sitting two desks behind me) was very
    disappointed to receive a very low mark on his exam. Anyways, he decided to rip his entire exam into
    three pieces. After he was done, my other friend (sitting one desk behind me) decided to break the
    terrible news to him: 'You know, our teacher takes the tests in again after this...' My
    friend that ripped up his test, just started laughing at himself. Then he started....
  6. Ti Basic: Pick A Number
    (1)
    Description Learn how to create a neat-o Game in TI Basic. Its basic premise is that someone
    picks a number, then they pass the calculator to their friend, and they try to guess the number.
    Once the successfully guess the number a message appears and says that they have won. I have also
    included a line that keeps users from choosing numbers greater than one-hundred. Please Enjoy.
    Try I Out Alright.... just input what you see below and I'll explain it a little below.
    CODE :ClrHome :Lbl 2 :Prompt A :A->X :If X>100 :Goto 2 &#....
  7. Html Div Help [resolved]
    help with the divs in ipb (1)
    hey guys, as you may know, i have ipb 2.3.4 set up on my site. i am currently using the centura
    skin and like it a lot. i have customised the header bar in terms of the logo, however also want a
    slab of text linking to the forums home at the top of the banner. i have so far managed to achieve
    this to work in firefox (see attached screenshot), however it just screws up in ie, opera and safari
    (i think). the link is here here is the code, both html and css, of the ipb header, and i have
    placed between stars the parts i have edited: CODE the css (only the ed....
  8. Css Multiclassing
    Applying more than 1 class to an element (2)
    There may be situations where you would like parts of a same style to be used through out your
    website but also need things a bit differently across certain elements. A combination of #ID and
    .Class selectors can usually do the job but there will be cases where a combination of of multiple
    classing would be better for the job. To try and make this situation more clear for you to
    understand lets take a look at an example. We have a website that has many sections in it that we
    need consistent styling too. A news section, forms, portfolio items. . How we need the styling ....
  9. Class Vs. Id?
    (7)
    CODE #random_div { random: random; random: random; } .random_div { random: random;
    random: random; } Ok... well.. above we have a id (the first one) and then the second one is
    a class. Could anyone please explain to me what the difference between the two is? And is one any
    better?....
  10. Make A Big Number!
    What is the largest number you can make with... (8)
    What is the largest number you can make with 3 one-digit numbers? You've no doubt heard this
    one before. The answer you all know and love is 9 ^ 9 ^ 9, or some 369-million digit number that
    appears in Pi somewhere but no one cares to memorize. Here are a few rules to that game: 1. The
    number must be less than infinity. 2. You cannot use unary operators. (Unary operators are operators
    that only require one argument to work, such as factorials. 1 + 2 = 3 is a binary operator, since it
    has two arguments, 1 and 2.) 3. If you use an iterated binary operator (one that i....
  11. Law And You Class - Competion
    (0)
    Okay in my law and you class we had to make up funny stories that explain terms such as battery and
    assault. Here are some of my stories. Battery Definition: Unlawful, unprivileged touching of
    another person. Situation: After school on Monday, Mike found Johnny started to beat him up because
    of an argument they had about basketball earlier that day. At the end of the fight, Johnny was
    bruised with a broken nose and two black eyes. Trespass Definition: Wrongful injury or
    interference with the property of another. Situation: One day, LaTwonda and Rasheeda, wanted t....
  12. History Class Project- Prohibition
    Prohibition (0)
    Today in history class we talked about the Roaring 20's and about prohibition. We also watched
    the Simpson's episode about prohibition. Before I start, here is the actual 18th amendment about
    prohibition. 1. After one year from the ratification of this article the manufacture, sale, or
    transportation of intoxicating liquors within, the importation thereof into, or the exportation
    thereof from the United States and all territory subject to the jurisdiction thereof for beverage
    purposes is hereby prohibited. 2. The Congress and the several States shall have con....
  13. Marijuana
    A paper I wrote for english class (3)
    I wrote an essay similar to this for my English class, I was wondering what some people thought
    about it or maybe some nice people can point out some typos and etc since i have no one to proof
    read to me. QUOTE Since the 1930s the DEA has been monitoring and illegalizing the use of
    drugs. Out of these “drugs” many of them have beneficial purposes in various medical
    fields while others were used for religious purposes as well. The Drug Enforcement Agency of the
    United States has been strict and manipulative in order to keep these substances illegal. One o....
  14. P.e. Class
    (2)
    I take gym like most students in High School and they make you wear uniforms and the whole picture
    and what not. Many kids today thogh, including myself, struggle with their weight and how to stay
    fit and how to keep up with other students. My life really snapped into perspective when I
    couldn't run the mile in under 10 minutes. When I was in Middle School I could, but when I
    reached the Hihg School level I was shocked that I had lost control that much of my weight. Today, I
    run 3 Miles with my dog before school and do 100 Sit-Ups before bed and I can run the mile in....
  15. Zk
    the number 1 Ajax Framework (2)
    ZK is an open-source Ajax Web framework that enables rich user interface for Web applications with
    little programming. Its an event-driven, component-based framework to enable rich user interfaces
    for Web applications. ZK includes an AJAX-based event-driven engine, a rich set of XUL and XHTML
    components and a markup language called ZUML (ZK User Interface Markup Language). With ZK, you
    represent your application in feature-rich XUL and XHTML components and manipulate them upon events
    triggered by user's activity, similar to what is done in desktop applications. Un....
  16. Php Email Validation
    A PHP data validation class with many functions (1)
    I've been reading through my old php book (PHP 4.1) and came across this data validation class.
    It can check a number of things ranging from telephone numbers , credit card number formats, email
    address and some others. I checked out some of the methods although I didnt expect it to work 100%
    because I've found source code errors thoughout the book and CD. I tested out a few of the
    methods to check and some of them did return expected results but some didnt either so the data
    validation class was not perfect and it didnt really bother me. The cool thing I found....
  17. The Story Of The Student Who Failed Writing Class
    (1)
    One of the students failed in writing class, it is unusual for a student to fail in an easy class
    like writing. When the teacher was asked about the raison he failed in the class he replied:
    honestly felows, the student cannot focus, every time he is given a topic to write about, he goes
    off topic. They then asked him to give them example of topics he wrote about. So the teacher said:
    Here is an example, write about the spring season… Spring is the most beautiful season in the
    year, during this season there are a lot of green pastures which allows the camel to feed....
  18. Do You Ever Skip Class?
    (73)
    well i used to skip almost every class especially algebra but not anymore because i realize that my
    education is a major part of my life and i refuse to fail but my english class is boring as f**k..
    have you ever skipped class? /huh.gif" style="vertical-align:middle" emoid=":huh:" border="0"
    alt="huh.gif" />....
  19. Alright, I'm Taking Computer Programming As A Class In School.
    (10)
    Is there anything I should personally be worried about or anything I really need to know? I'm
    pretty much good with computers and such and pretty much spend my whole life on them, lol.....
  20. Final Spec's Of My Computer Build For My Hardware Class
    (11)
    Well I got two weeks left in the semester and on August 18th I will have built my first computer
    from scratch, now hopefully during the rest of the year I will have build up a series of topics on
    computer hardware and tutorials on building a computer from scratch that most of you will never have
    to buy a pre built system again /biggrin.gif" style="vertical-align:middle" emoid=":D" border="0"
    alt="biggrin.gif" />. With that being said this is the final specs of the computer I will be
    building, after I had a fluke with my floppy drive (had the wrong one). Keyboard &....
  21. Eclipse Exporting .jar Files
    Could not find main class. Program will exit. (5)
    I need help! I've been using eclipse for a while making little applets, and now I've
    decided to look at some tutorials on how to make simple applications. I've found a pretty good
    tutorial that tells you how to make a helloWorld app with swt and jFace, and also has an example
    file explorer that you can make. They both work perfectly from inside eclipse, but when I try and
    export either one into a .jar file, they don't work anymore. It comes up with a message saying
    "Could not find main class. Program will exit." In the little wizard it has for....
  22. Mathematical Proof
    ...that there is no largest prime number (11)
    In math, a proof is basically just that, proof that something is true. Proofs must be rigid, they
    cannot be based on assumptions. For example, just because we keep finding bigger and bigger prime
    numbers, it does not mean there are infinitely many. However, there is a proof for that. First,
    assume that there is, in fact, a largest prime number. Call it "P." That is, there is no prime
    that is greater than P. (It's OK to assume things like this in a proof sometimes; for example,
    it's OK here because we intend to prove that our assumption is wrong, that it le....
  23. My Life After High School
    an essay for english class (2)
    Melody and Musical Centricity Introduction Wouldn’t it be nice if everyone was
    musically talented? Well, for those who are, they have the potential to make it big, to make a
    living off of their skills, to become nationally known. The likelihood is very slim and very few
    people make it to stardom. The window is small and it takes every ounce of passion to make it, and
    I think that I have that passion. I will not leave it to chance, however, for I will still go to
    college and have a part-time job to support my band. I would like to live in a nice, sunny p....
  24. English Class Speech
    what do you think? (7)
    ok the topic is pro capital punishment: “Have you ever thought about how many criminals escape
    punishment, and yet, the victims never have a chance to do that? Are crime victims in the United
    States today the forgotten people of our time? Do they receive full measure of justice?.” These
    are just a few of the questions posed by the late director of the FBI J. Edgar Hoover. Criminals
    on death row have the chance to make a will and prepare for their death, while some victims can
    never do it. My opponents may argue that the death penalty has no deterrent effect, but....
  25. Advice On Impressing Someone In My Class
    in post (8)
    Ya well basically i need help with impressing/asking out someone, i have plety of oppurtunities in
    my 4th hour class she sits behind me in my 5th hour class she sits to the right of me and in 6th
    hour she sits diagonal to me so i have oppurtunities to talk to her but i dont know what to do,last
    time i had a crush on someone i never built up courage to ask her out or talk to her much and i
    ended up just like hating myself whenever i saw her...not like hitting myself lol jus mentally and i
    ended up just hating it whenever i saw her for 2 years and i finally just let it go ....
  26. Google A Number?
    (48)
    when i was in 5th grade, which was 5 years ago, this was right when google first came out i think...
    anyways, i remember my 5th grade teacher telling me that the word google was the biggest number
    possible and that it was bigger than infinity. Back then i believed it but then you really think
    about it, how is a number even possibly bigger than infinity if infinity goes on FOREVER? and is
    googe EVEN a number????? anybody know?....
  27. Need Help With C Program To Test If A Number Is Prime
    Ending unexpectedly somewhere near for-loop (12)
    CODE #include <stdio.h> main() {       printf("Enter a number:
    ");              int n;       scanf("%d", &n);              if(n ==
    2)            printf("%d is prime", n);       else if(n % 2 == 0 || n <
    2)            printf("%d is not prime", n);       else       {            int x;
               for(x = 0; x < (int)sqrt((double)n); x++)
                    if(n % x == 0)                 {                      printf("%....
  28. June 6th 2006 - The Devils Number
    Possibly the end of the world? (113)
    Ok, I don't want to start any religious fights here, that's not what this topic is meant
    for. So PLEASE hold the religious comments. I was at school one day, I turned to a friend and said
    "I bet the world will end on June 6th of this year". Now I think they'd know what I meant(goth
    kids, ya, no I'm not one). But they didn't! So I sat there and explained it, all of a
    sudden "Bing" the light in there brain goes off, they said that's really a possibilty. For
    those of you who don't get it; June 6th, 2006 6-6-06 Or without the 0, 6-6-6, 666 W....
  29. Php Unique Hit Counter
    Count page hits with php. (29)
    Hello all, Here is a neat and helpful PHP script that can count unique page views on your website.
    First you need to open up a new page in your text editor and paste in this code. CODE <?php
    $filename = "hits.txt"; $file = file($filename); $file =
    array_unique($file); $hits = count($file); echo $hits; $fd
    = fopen ($filename , "r"); $fstring = fread ($fd , filesize
    ($filename)); fclose($fd); $fd = fopen ($f....
  30. Number Guessing Game
    number guessing game (9)
    do you still have the code for that number guessing game?....

    1. Looking for count, number, divs, class

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for count, number, divs, class

*MORE FROM TRAP17.COM*
advertisement



Count Number Of Div's By A Class Name



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE