Rewriting HTML code using javascript
I have some markup here that I need to reformat using javascript. Basically, I have this code:
<div id="images">
<img src="01.jpg">
<img s开发者_如何学编程rc="02.jpg">
<img src="03.jpg">
<img src="04.jpg">
<a id="src" href="01.jpg"></a>
<a id="src" href="02.jpg"></a>
<a id="src" href="03.jpg"></a>
<a id="src" href="04.jpg"></a>
</div>
and I want javascript to rewrite the code so that the images are placed inside the anchors. Like this:
<div id="images">
<a id="src" href="01.jpg"><img src="01.jpg"></a>
<a id="src" href="02.jpg"><img src="02.jpg"></a>
<a id="src" href="03.jpg"><img src="03.jpg"></a>
<a id="src" href="04.jpg"><img src="04.jpg"></a>
</div>
any ideas?
<script>
var div = window.document.getElementById("images");
var anchors = div.getElementsByTagName("A");
var imgs = div.getElementsByTagName("IMG");
for (var i = anchors.length - 1; i >= 0; i--) {
anchors[i].appendChild(imgs[i]);
}
</script>
General strategy:
- Get a reference to the "images" div
- Create a temporary object to store images, e.g.
var imgs = {};
- Loop over all
img
elements within the div. For each element:- Add each element to
imgs
, using itssrc
as the key
- Add each element to
- Loop over all
a
elements within the div. For each element:- Lookup the image from
imgs
using the element'shref
attribute - Remove the
img
from its current location, and re-insert it within the body of thea
.
- Lookup the image from
精彩评论