Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to get link text

Tags:

javascript

My HTML looks like this:

<div class="col-md-2" id="myName1">
  <p>
    <a href="/something/121212">Get This Text</a>
  </p>
</div>

The question is how do I get the text "Get this Text"

Something like this, but getting that text which is wrapped in the p and a tags:

function () {
  return document.getElementById('TextID');
}
like image 510
jonmrich Avatar asked Aug 29 '26 21:08

jonmrich


2 Answers

You can search for the first p inside your myName1 element, then the first a within that.

var e = document.getElementById('myName1').
        getElementsByTagName('p')[0].
        getElementsByTagName('a')[0];

var theText = e.innerHTML;

console.log(theText);

// or, in sufficiently-modern browsers

e = document.querySelector('#myName1 p a');
theText = e.innerHTML;

console.log( theText );
<div class="col-md-2" id="myName1">
<p>
<a href="/something/121212">Get This Text</a>
</p>
</div>
like image 194
Paul Roub Avatar answered Sep 03 '26 15:09

Paul Roub


Try adding the following in your function:

return document.querySelector('#myName1 p a').innerHTML
like image 43
Thomas Avatar answered Sep 03 '26 15:09

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!