Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an attributes value of the ALT attribute of a hyperlink

My a-tag (link) contains innerHTML which is an image like this:

.innerHTML = <img alt="hello world" src="/Content/Images/test.png">

How can I get the text of the alt attribute with JQuery?

like image 388
Elisabeth Avatar asked Dec 03 '22 00:12

Elisabeth


1 Answers

You really don't need jQuery. If you have the a element you can do this:

// lets call the anchor tag `link`
var alt = link.getElementsByTagName('img')[0].alt; // assuming a single image tag

Remember attributes map to properties (most), and unless the property is changed, or the attribute, the two should reflect the same data (there are edge cases to this, but they can be handled case-by-case).

If you truly do need the attribute there is

var alt = link.getElementsByTagName('img')[0].getAttribute('alt');

Last scenario is if you only have the image tag as a string.

var str = '<img alt="hello world" src="/Content/Images/test.png">';
var tmp = document.createElement('div');
tmp.innerHTML = str;
var alt = tmp.getElementsByTagName('img')[0].alt;

If you must use jQuery (or just prefer it) then the other answer provided by Alexander and Ashivard will work.

Note: My answer was provided for completeness and more options. I realize the OP asked for jQuery solution and not native js.

like image 153
rlemon Avatar answered Feb 22 '23 23:02

rlemon