Search code examples
htmlcsscss-content

How to get image attribute with content?


I can get attribute from tag <a> but I can not get it from <img>. what can i do ?

DEMO

HTML

<img src="http://placehold.it/50x50" alt="Some alt"/>
<br/>
<a href="#" alt="Some alt">test link</a>

CSS

img:after{
    content:attr(alt);
    margin-left:10px;
}
a:after{
    content:attr(alt);
    margin-left:10px;
}

Solution

  • according to the @Passerby comment it is not possible with CSS:

    According to MDN, ::after "matches a virtual last child of the selected element", and because can not have child, it won't have any ::after or ::before. Same applies to input too.

    so I wrote this JQuery code:

    DEMO

    var $imageAlt = '<span class="after">'+$("#image").attr("alt")+'</span>';
    $("#image").after($imageAlt);