Document.getElementsByClassName show before

Asked

Viewed 38 times

-3

I wanted you to show me how many "twitter-tweet" classes you have in html at the top, not at the bottom. if I place at the top appears "0 videos" and if I place at the bottom appears the right amount.

<head>
<title>Passinho</title>
<link rel="stylesheet" type="text/css" href="/style.css">
</head>
<body>

<br><br><br><h1>Passinho: <script>
var len = document.getElementsByClassName("twitter-tweet").length;
document.write(len);
console.log(len);
</script> videos</h1><br><br><br>   <-- aqui fica 0 videos

<!-- 64 -->
<blockquote class="twitter-tweet"><p lang="pt" dir="ltr">ESSE VÍDEO É VICIANTE  <a href="https://twitter.co/blLqQhWes6">pic.twitter.com/blLqQhWes6</a></p>&mdash; PASSINHOS E DANCINHAS (@ilovepassinhorj) <a href="https://twitter.com/ilovepassinhorj/status/1205874013920206850?ref_src=twsrc%5Etfw">December 14, 2019</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<!-- 63 -->
<blockquote class="twitter-tweet"><p lang="und" dir="ltr"> <a href="https://twitter.co/orvqANs3VQ">pic.twitter.com/orvqANs3VQ</a></p>&mdash; Bia Das Dancinhas (@Ofcquebradeira) <a href="https://twitter.com/Ofcquebradeira/status/1207007235563499520?ref_src=twsrc%5Etfw">December 17, 2019</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<!-- 61 -->
<blockquote class="twitter-tweet"><p lang="pt" dir="ltr">Já que pedirammm ‍♂️<br>Tivemos que quebrar <a href="https://twitter.com/eilaryssamoraes?ref_src=twsrc%5Etfw">@eilaryssamoraes</a> <a href="https://twitter.co/Sp3dipMm0o">pic.twitter.com/Sp3dipMm0o</a></p>&mdash; Lc Quebradeira (@lucasalveslc1) <a href="https://twitter.com/lucasalveslc1/status/1201655334496067586?ref_src=twsrc%5Etfw">December 3, 2019</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<br><br><br><h1>Passinho: <script>
var len = document.getElementsByClassName("twitter-tweet").length;
document.write(len);
console.log(len);
</script> videos</h1><br><br><br> <-- aqui mostra a quantidade certa de videos
queria fazer isso só que na parte lá de cima no primeiro <h1>

1 answer

4

It is because the elements do not exist or were not rendered before the first script, meaning they only exist after the first script, or you use the load event to check when the page loaded:

window.addEventListener('load', function () {
    var len = document.getElementsByClassName("twitter-tweet").length;
    console.log(len);
});

Or prefer the event DOMContentLoeaded (is an event of the object document) which will not need everything to load (like images and other scripts), only HTML:

document.addEventListener('DOMContentLoaded', function () {
    var len = document.getElementsByClassName("twitter-tweet").length;
    console.log(len);
});

Browser other questions tagged

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