1

I'm working on a userscript for YouTube and I need to retrieve the href attribute of an <a> tag through the class name.

This was my attempt but it just returned "undefined":

var x = document.getElementsByClassName("mix-playlist").getAttribute("href");
console.log(x);
<a class="XY XY XY mix-playlist XY" href="XY"></a>

Thanks for your help!

Nevermind, I figured it out. I just had to move it into this function: document.addEventListener("DOMContentLoaded", function() {

and split the resulting array.

Sorry for the duplicate but I just couldn't gather much information after looking through stackoverflow questions for 20 minutes.

Sv443
  • 708
  • 1
  • 7
  • 27
  • 4
    `var x = document.getElementsByClassName("mix-playlist")[0].getAttribute("href");` – Mamun May 23 '18 at 23:06
  • @Mamun that returns "Execution of script failed! document.getElementsByClassName(...)[0] is undefined" – Sv443 May 23 '18 at 23:08
  • 2
    May be you need put the code after HTML.. – Mamun May 23 '18 at 23:10
  • @Sv443 that likely means that the element is not yet in the DOM when you're trying to access it. – Jared Smith May 23 '18 at 23:10
  • @Mamun I don't have much power over that with my tampermonkey addon but the script runs multiple times even when the element has fully loaded. – Sv443 May 23 '18 at 23:12
  • JavaScript: var elems = document.getElementsByTagname("A"); for (var i=0;i –  May 23 '18 at 23:14
  • Try to search for "how to run code after DOM loaded in JavaScript?" – Mamun May 23 '18 at 23:14
  • If the JavaScript is in your ``, which it should be for external caching reasons, then you need to put your JavaScript *(on the external JS page)* in a load Event, like `addEventListener('load', function(){ /* Elements are defined since page is loaded *});` or `var old = onload; /* change old var name if using technique on other pages */ onload = function(){ if(old)old(); /* execute if there is already a load Event - Elements are available now */ }` – StackSlave May 23 '18 at 23:18

0 Answers0