Q.H.
Q.H.

Reputation: 1456

When getting element by ID, how can I grab the contents within the section?

In javascript when I call the "getElementById" method, how can I access the information within that ID section, such as a link for example?

<p id="demo"><a href="someWebsite.com">some link</a></p>

<button onclick="myFunction()"> Grab Link</button>

<script>
    function myFunction() {
        var thisLink = document.getElementById("demo");
        thisLink.(functionToGetSomeLink); //any way to get the link???
}
</script>

Upvotes: 0

Views: 474

Answers (3)

alex bennett
alex bennett

Reputation: 872

you can chain another method onto document.getElementById("demo"); such as:

document.getElementById("demo").value

or

document.getElementById("demo").text

Upvotes: 1

www139
www139

Reputation: 5237

Please tell me if I didn't understand the question correctly.

You can just get the first (only) child of the #demo div and get the href attribute. This example only uses a couple lines but it is possible to further simplify it.

function myFunction() {
  var thisLink = document.getElementById("demo").children[0].href;
  alert(thisLink);
  console.log(thisLink);
}
<p id="demo"><a href="someWebsite.com">some link</a>
</p>
<button onclick="myFunction()">Grab Link</button>

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

Use

querySelector

to access the anchor

var anchorTag = document.querySelector('#demo a');

var href = anchorTag.getAttr('href');

Upvotes: 0

Related Questions