Reputation: 1456
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
Reputation: 872
you can chain another method onto document.getElementById("demo"); such as:
document.getElementById("demo").value
or
document.getElementById("demo").text
Upvotes: 1
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
Reputation: 55750
Use
querySelector
to access the anchor
var anchorTag = document.querySelector('#demo a');
var href = anchorTag.getAttr('href');
Upvotes: 0