1

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 string:

<img alt="main-logo" src="main-logo.png">

So how can I have main-logo to be red?
Thank you!

EDIT

Thanks to techfoobar for the solution and everyone else that helped!
Here is a jsFiddle Example.

m.spyratos
  • 3,823
  • 2
  • 31
  • 40

2 Answers2

3

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:

&lt;img alt="<span class='red'>main-logo</span>" src="main-logo.png"&gt;

And in your CSS, add:

span.red {
    color: red;
}
Community
  • 1
  • 1
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • I +1ed this, but the reg exp probably could use some work since it is really limited to what can be in the value. – epascarello May 21 '13 at 13:41
  • Yes, especially the `[a-z0-9\s-]*` bit. – techfoobar May 21 '13 at 13:42
  • @techfoobar, That was my very first thought. I tried it, but it actually displays this: `<span class='red'>main-logo</span>`. So it doesn't add the `span` as `html`, but as a string. – m.spyratos May 21 '13 at 13:47
  • 3
    A small problem the user will probably face: the img outerHTML will have to be html-encoded before the replace, so when it's displayed in a container, only the injected span will be parsed as actual tags. – bfavaretto May 21 '13 at 13:48
  • @bfavaretto - That is a huge problem. This wont work directly! You're totally right. Din think of that. – techfoobar May 21 '13 at 13:52
  • Made some mods to take html-encoding into account. Credit: [http://stackoverflow.com/a/1219983/921204][1] – techfoobar May 21 '13 at 13:58
  • @techfoobar, Thank you very much! That was a really big help! :) – m.spyratos May 21 '13 at 14:13
-1

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>
Sumit
  • 1,619
  • 1
  • 11
  • 24