How To Style An Image's Alt Attribute
I am trying to display the (outer)html of an img tag, but I want the alt attribute to be in red. The way I get the string: var img_outerHTML = img[0].outerHTML; This gives me the
Solution 1:
Assuming you are trying to display the outer HTML as such in another element, you can do:
var s = '<img alt="main-logo" src="main-logo.png">';
// As pointed out by user bfavaretto, we need to html-encode it before
// injecting the <span>
s = $('<div/>').text(s).html();
s = s.replace(/alt=\"([a-zA-Z0-9\s-]*)\"/, 'alt="<span class=\'red\'>$1</span>"');
Once done, this will transform the HTML string to (Note: that everything other that the span will be HTML encoded. Credit: https://stackoverflow.com/a/1219983/921204)
<img alt="<span class='red'>main-logo</span>" src="main-logo.png">
Actually, it will be:
<img alt="<span class='red'>main-logo</span>" src="main-logo.png">
And in your CSS, add:
span.red {
color: red;
}
Solution 2:
This can also be done by CSS only.
just wrap yout img tag into span tag and apply red color to that span.
try this
<span style="color: red;"><img alt="main-logo" src="main-logo.png"></span>
Post a Comment for "How To Style An Image's Alt Attribute"