简体   繁体   中英

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.

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'));
}

There's an easy solution using jQuery's show() method, as it shows all elements of a given class:

$('.but b_yt').show();

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

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

在此处输入图像描述 `

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM