开发者

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:

  1. Get a reference to the "images" div
  2. Create a temporary object to store images, e.g. var imgs = {};
  3. Loop over all img elements within the div. For each element:
    • Add each element to imgs, using its src as the key
  4. Loop over all a elements within the div. For each element:
    1. Lookup the image from imgs using the element's href attribute
    2. Remove the img from its current location, and re-insert it within the body of the a.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜