Nemo-Omen
Nemo-Omen

Reputation: 117

How do I count the number of elements by classname, and turn the result into a variable?

I need to count how many of an element I have, but I'm not having much luck. Element sample:

<textarea type="text" data-class-changer="question" class="questioninputcss" data-integer-question="866"></textarea>

Moving on to my code,

I've tried two things. Here's the first, with its response:

        var testCountPre = document.getElementByClassName('questioninputcss');
        var testCount = testCountPre.getElementsByTagName('textarea').length;

Uncaught TypeError: undefined is not a function


And the second, with its response:

    var testCount = ($(".questioninputcss textarea").length);
    var_dump(testCount);

Number(1) 0

Edit for clarification: I'm using a var_dump script that works in javascript.

Upvotes: 0

Views: 85

Answers (3)

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

try this...

var testCount = ($("textarea.questioninputcss").length);
console.log(testCount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea type="text" data-class-changer="question" class="questioninputcss" data-integer-question="866"></textarea>

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

With jQuery, combine the selectors like below. Your script is trying to find textarea elements which are descendants of an element with class questioninputcss

var testCount = $("textarea.questioninputcss").length;

Without jQuery, use querySelectorAll()

var testCount = document.querySelectorAll('textarea.questioninputcss').length;

getElementsByClassName()(there is a spelling mistake in your code) returns a HTMLCollection, so it does not have a method named getElementsByTagName()

Upvotes: 1

easywaru
easywaru

Reputation: 1153

Try this.

($("textarea.questioninputcss").length);

Upvotes: 1

Related Questions