0

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.

5
  • thats expected behaviour as alert() will stop any further execution until you click "ok" on dialogue Commented Nov 1, 2019 at 14:27
  • It is the right output for console.log. Commented Nov 1, 2019 at 14:27
  • Can I force console.log to print just link that is in the button? Commented Nov 1, 2019 at 14:31
  • Try setting x to [...document.getElementsByClassName("but b_yt")], it will spread the HTML data collection into an array of elements Commented Nov 1, 2019 at 14:32
  • @GammaGames it gave me [object HTMLCollection] output. Commented Nov 1, 2019 at 14:35

2 Answers 2

1

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'));
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

This returns everything between tags, but not source of the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.