Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript parse html, modify anchor tags that contain images

I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.

I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify 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 to be:

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

So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.

To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.

To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json

The HTML code that contains the tags are found at "feed > entry > content > $t"

Am currently working with Mootools 1.3

Any ideas? Thanks.

like image 978
Nicekiwi Avatar asked Nov 14 '22 18:11

Nicekiwi


1 Answers

First, put it in a new element that does not exist on the page, then modify it as usual:

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";
});

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

like image 117
gilly3 Avatar answered Dec 04 '22 11:12

gilly3