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=jso开发者_开发知识库n
The HTML code that contains the tags are found at "feed > entry > content > $t"
Am currently working with Mootools 1.3
Any ideas? Thanks.
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/
In straight 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;
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');
精彩评论