Reputation: 61
I am not a Javascript expert at all but I'm not sure how to accomplish this. I have a link on a page that has a link structured similar to the code below. How can I extract the value of either the title reference or the Link? I figure that innerHTML would need to be used to get Link text but I can't get the element by ID or tag name.
<a href="#" title='titlevalue'>Link</a
Upvotes: 6
Views: 11325
Reputation: 3046
You need to add a specific ID to your link. And then you can access it directly and get the valued you need. Here is an example: First, add an id to your link
<a href="#" id="myLink" title='titlevalue'>Link</a>
Then get it with javascript
var title = document.getElementById('myLink').title;
var html = document.getElementById('myLink').innerHTML;
And altogether:
var title = document.getElementById('myLink').title;
var html = document.getElementById('myLink').innerHTML;
console.log("Title: " + title);
console.log("HTML: " + html);
<a href="#" id="myLink" title='titlevalue'>Link</a>
Upvotes: 1
Reputation: 409
You can also use data attributes like this:
<a href="#" data-title='titlevalue'>Link</a>
--> Instead of the title
attribute you convert in into a data attribute like this: data-title
And in your javascript:
const link = document.getElementsByTagName('a')[0];
console.log(link.dataset.title);
And this should log: titlevalue
You can read more about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
Upvotes: 1
Reputation: 10194
You can get the elements with tag name
using getElementsByTagName
function. This will return array of elements with same tag name
.
From that array, you can get the element you want and,
using getAttribute
function, you can get the value of the specific attribute
.
const elements = document.getElementsByTagName('a');
const target = elements[0];
console.log('Href : ' + target.getAttribute('href'));
console.log('Title : ' + target.getAttribute('title'));
<a href="#" title='titlevalue'>Link</a>
Upvotes: 1