remove the number of elements of the class from a label with javascript?

2

I wanted to know how I can get the number of elements in JavaScript which function should I use I was looking for but I did not find it. Code example:

var parentDOM = document.getElementById("parent-id");

var test=parentDOM.getElementsByClassName("test");//test is not target element
console.log(test);//HTMLCollection[1]

var testTarget=parentDOM.getElementsByClassName("test")[0];//here , this element is target
console.log(testTarget);//<p class="test">hello word2</p>
<div id="parent-id">
    <p class="prueba">hello word1</p>
    <p class="test">hello word2</p>
    <p class="test">hello word3</p>
    <p class="test">hello word4</p>
</div>

How can I know the number of elements in class test . and if not, it is possible to return it as a list and separate it each one. How could it be?

    
asked by Sergio Ramos 12.02.2018 в 17:01
source

2 answers

3

You can obtain by selecting them with querySelectorAll, and as a condition the div (Parent) and the class you want to select.

let cantidad = document.querySelectorAll('#parent-id .test').length;
console.log('cantidad:', cantidad);
<div id="parent-id">
  <p class="prueba">hello word1</p>
  <p class="test">hello word2</p>
  <p class="test">hello word3</p>
  <p class="test">hello word4</p>
</div>
    
answered by 12.02.2018 в 17:07
2

Good morning, just use the javascript length function, the result in this case is 3.

<script>
    var parentDOM = document.getElementById("parent-id");

    var test=parentDOM.getElementsByClassName("test");//test is not target element
    console.log(test.length);//HTMLCollection[1]

    var testTarget=parentDOM.getElementsByClassName("test")[0];//here , this element is target
    console.log(testTarget);//<p class="test">hello word2</p>
</script>
    
answered by 12.02.2018 в 17:08