4

I'm trying to get the value of the 'a' tag from a website. I'm running the code below in the console of Google Chrome.

document.querySelector('#container > article:nth-child(1) > div > h1 > a');

Executing that returns this tag:

<a class="name-link" href="/shop/blarg/foo/bar">blarg</a>

I'm trying to get 'blarg' returned, preferably in a variable. I have tried the following:

document.querySelector('#container > article:nth-child(1) > div > h1 > a').value;

However it simply returns 'undefined'. Any help would be much appreciated, thank you

aboruchovas
  • 45
  • 2
  • 5
  • [https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent) – Olafant Feb 28 '19 at 10:48

4 Answers4

3

You should select innerHTML

document.querySelector('#container > article:nth-child(1) > div > h1 > a').innerHTML;

You can also edit that html like this

document.querySelector('#container > article:nth-child(1) > div > h1 > a').innerHTML="new value";
pavelbere
  • 964
  • 10
  • 21
2

This should do the trick for you. To get innner text instead of .value you should use .text

document.querySelector('#container > article:nth-child(1) > div > h1 > a').text;
Shubham Jain
  • 930
  • 1
  • 14
  • 24
2

Use the textContent property to get the text as a tag does not have an value property and will return undefined

console.log(document.querySelector('#container > article:nth-child(1) > div > h1 > a').textContent);
<div id="container">
    <article>
      <div>
        <h1>
          <a class="name-link" href="/shop/blarg/foo/bar">blarg</a> 
        </h1>
      </div>
    </article>
    <article></article>
</div>
Shubham Jain
  • 930
  • 1
  • 14
  • 24
ellipsis
  • 12,049
  • 2
  • 17
  • 33
2

Use innerHTML instead of value. i.e.

document.querySelector('#container > article:nth-child(1) > div > h1 > a').innerHTML;

querySelector returns the first web page element (object) that matches the specified group of selectors. So you can not use value with the return result of querySelector.

Awad Maharoof
  • 2,260
  • 1
  • 24
  • 36