tags:

views:

76

answers:

2

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 src="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?

A: 

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.
harto
(assuming no particular ordering for images and/or links)
harto
+2  A: 
<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>
Ah well. Give a man a fish, etc.
harto
thanks for doing it old school.
Alfonse