Get an attributes value of the ALT attribute of a hyperlink

前端 未结 3 1383
无人及你
无人及你 2021-01-14 02:08

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

.innerHTML = \"hello
相关标签:
3条回答
  • 2021-01-14 02:30

    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.

    0 讨论(0)
  • 2021-01-14 02:30

    use this.

    var altName=$('a img').attr('alt');
    
    0 讨论(0)
  • 2021-01-14 02:34

    Being $a your <a/> element.

    Using jQuery you can do:

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

    Or, using pure JavaScript:

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

    ​ See it here.

    0 讨论(0)
提交回复
热议问题