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
$('#my-div a'). click(function() { var txt = $(this). text(); console. log(txt); });
Use the title attribute for your links when you can provide additional information about that link and/or the page it goes to. For example, if your anchor text just says click here, give your users a better idea of what they'll get if they click on the link (scroll over the “click here” link to see what I mean).
Link title attribute. The Link title is an optionally defined attribute to give additional, advisory information about a linked web site. It helps clarify or further describe the purpose of a link that a recipient should know before clicking it.
Definition and Usage The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!
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>
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With