fejker
fejker

Reputation: 11

How to display multiple elements to html using javascript?

When I try to print elements found by function, just the first one is being printed.

Tried multiple printing methods. For now alert() is working fine, but I can't copy the content.

    function test() {
       var x = document.getElementsByClassName("but b_yt");
       for (i = 0; i < x.length; i++) { 
          alert(x[i]);
       }
    }

Every other printing methods doesn't print at all, prints just first one or something like [HTML Data Collection]. console.log works, but it gives me the whole HTML code of button.

Upvotes: 0

Views: 321

Answers (2)

Shadab Ali
Shadab Ali

Reputation: 439

may be a noob approach this will give you innerhtml of each h1

<h1 class="abc">hello</h1>
<h1 class="abc">helsfvdfbbdfbdlo</h1>

enter image description here`

var s = document.getElementsByClassName('abc');

for (i = 0; i < s.length; i++) {
    console.log(document.getElementsByClassName('abc')[i].innerText);
}

Upvotes: 0

dmitri7
dmitri7

Reputation: 193

You can get href attributes this way:

let elements = document.getElementsByClassName('but b_yt');

for(let i = 0; i < elements.length; i++) {
    let element = elements[i];
    console.log(element.getAttribute('href'));
}

Upvotes: 1

Related Questions