Javascript parse html, change anchor tags containing images

I have a vague idea of ​​how to do this, but I was hoping that more experienced developers might have a simpler solution.

I have a sting of HTML code from a JSON feed and where there is an “a” tag with images inside the “a” tag that I want to change and add attributes. Example:

<a style="color:000;" href="images/image.jpg">
    <img width="100" height="20" src="images/image_thumb.jpg" />
</a>

I would like to change it as:

<a style="color:000;" href="images/image.jpg" rel="lightbox" >
    <img width="100" height="20" decoy="images/image_thumb.jpg" />
</a>

So, adding the attribute to the "a" tag and changing the attribute to the "img" tag. There may be several links inside the HTML code with and without images and other HTML code surrounding them.

To be clear, this is NOT modifying the HTML that is already displayed on the page, it is changing the line of code before it is shown.

, JSON: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json

HTML, , "feed → content > $t"

Mootools 1.3

? .

+5
3

, , :

var container = new Element("div", { html: yourHTML });
container.getElements("a img").forEach(function(img){
    var link = img.getParent("a");
    img.decoy = img.src;
    img.removeAttribute("src");
    link.rel = "lightbox";
});

: http://jsfiddle.net/XDacQ/1/

+1

JS

var a = document.createElement('div');

// put your content in the innerHTML like so
a.innerHTML = '<a style="color:000;" href="images/image.jpg"><img width="100" height="20" src="images/image_thumb.jpg" /></a>';

var b = a.firstChild;
b.rel = 'lightbox';
var c = b.firstChild;
c.setAttribute('decoy', c.src);
c.src = null;

// now you have your a tag
var newA = a.innerHTML;
0

Dumbest regexp

var string = '<a style="color:000;" href="images/image.jpg">="images/image_thumb.jpg" /></a>',
    text = '';

text = string.replace('href', 'rel="lightbox" href');
text = text.replace('src', 'decoy');
0

All Articles