Get an attributes value of the ALT attribute of a hyperlink

前端 未结 3 1496
无人及你
无人及你 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 = 'hello world';
    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.

提交回复
热议问题