Check the amount of elements within a div with an id within a javascript class?

Asked

Viewed 612 times

0

I’m trying to access a id within a css class to check the amount of existing paragraphs within it. In javascript how I could do it in that case?

Example:

<div class="classe">
    <div id="algo">
       <p>paragrafo1</p>
       <p>paragrafo2</p>
       <p>paragrafo3</p>
    </div>
</div>
  • 1

    forehead alert(document.querySelectorAll('#algo p').length);

1 answer

2


You can use the document.querySelectorAll to select multiple elements with a CSS selector.

In your case it could be so:

var qtd = document.querySelectorAll('#algo p').length;
console.log('A quantidade de <p>\'s é', qtd);
<div class="classe">
    <div id="algo">
       <p>paragrafo1</p>
       <p>paragrafo2</p>
       <p>paragrafo3</p>
    </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.