Search code examples
javascripthtmljquery-selectorstampermonkey

selecting an element by a tag name and class name


I am trying to capture a tags inside a header with known class name.

inspect element:

<h3 class="c-card__title">
                    <a href="https://www.springer.com/book/9783030873233" data-track="click" data-track-action="clicked article" data-track-label="article-0">SARS-CoV-2 Spike Protein Convergent Evolution
                    </a>
                </h3>

my code:

var elements = document.getElementsByClassName("c-card__title").getElementsByTagName('a');
var vals = [];
for(var i=0;typeof(elements[i])!='undefined';vals.push(elements[i++].getAttribute('href')));
     for (var j = 0;typeof(vals[j])!='undefined'; ++j) {
     window.open(vals[j]);

I run it in the browser console but it gives me the following error:

VM1065:4 Uncaught TypeError: document.getElementsByClassName(...).getElementsByTagName is not a function
    at <anonymous>:4:66

Solution

  • You can't use getElementsByTagName method after getElementsByClassName, you should use:

    document.querySelectorAll(".c-card__title > a");
    

    Take a look to this