Get attribute value of hyperlink ALT attribute

My tag (link) contains innerHTML, which looks like this:

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

How can I get alt attribute text using jQuery?

+4
source share
3 answers

Be $a your <a/> element.

With jQuery you can:

 $("img", $a).first().attr("alt"); 

Or using pure JavaScript:

 var $img = $a.getElementsByTagName("img")[0]; console.log($img.alt); 

See here.

+8
source

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

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

Remember that attributes are mapped to properties (most often), and if the property is not changed or the attribute, they should reflect the same data (this includes extreme cases, but they can be processed in each case).

If you really need an attribute,

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

The final 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 should use jQuery (or just prefer), then another answer provided by Alexander and Ashivar will work.

Note. My answer has been provided for completeness and additional features. I understand that the OP requested a jQuery solution, not native js.

+6
source

use this.

 var altName=$('a img').attr('alt'); 
+1
source

All Articles