0

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?

3
  • 2
    By the way, you can't have id="src" in more than one place. Each id value must be unique across the whole document. Commented Jan 20, 2010 at 1:13
  • Do the links serve any purpose with javascript disabled? Might be easier to create the links with the jQuery if that's the case Commented Jan 20, 2010 at 1:37
  • not sure why i added the id Chris. We can remove it. It was easier to do this using jquery Gareth. see stackoverflow.com/questions/2098600/… for what we came up with. Commented Jan 20, 2010 at 3:28

2 Answers 2

4
<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>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

(assuming no particular ordering for images and/or links)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.