2

I have a nav here with li inside is an anchor tag and span which consist of the text. What I want to achieve is to replace all span in the nav using jquery replaceWith however, I can't seem to make it work. This is the code I made. Any Idea what my error is?

<script>
$( document ).ready(function() {
    //store img in an array.
    var imgArray= [ "<img class=\"imgNav\" src=\"https://irp-cdn.multiscreensite.com/abc3fe9a/dms3rep/multi/services_icon_1-123x123.png\"/>",
    "<img  class=\"imgNav\" src=\"https://irp-cdn.multiscreensite.com/abc3fe9a/dms3rep/multi/services_icon_4-123x123.png\"/>","<img  class=\"imgNav\" src=\"https://irp-cdn.multiscreensite.com/abc3fe9a/dms3rep/multi/services_icon_66-123x123.png\"/>" ];



        $('.dmUDNavigationItem_010101661768 > span.navItemText').replaceWith(imgArray[0]);
        $('.dmUDNavigationItem_010101628177 > span.navItemText').replaceWith(imgArray[1]);
        /* if I put this third one in the script it doesn't work.
        $('.dmUDNavigationItem_010101420041 > span.navItemText').replaceWith(imgArray[2]);
        */



});
</script>

This is my HTML link in jsbin. http://jsbin.com/magofarivi/edit?html,output

icedev
  • 215
  • 1
  • 17
  • That should be working. Here is a simplified example using your JS: [Codepen](http://codepen.io/anon/pen/RRjAvG). My guess would be your class name is incorrect in that third one but we can't tell since the html isn't provided. Also, does it need to be in a loop? Right now, it will run those `replaceWith()` calls three separate times for each selector. – Derek Story Jul 12 '16 at 03:31
  • I was using the forloop to console.log the img array in my first trials. – icedev Jul 12 '16 at 04:53
  • Please only provide the relevant code. If you are no longer using it, it shouldn't be included in the question. Furthermore, your code still works as expected with the html in the JS Bin. It must be something else. [Codepen](http://codepen.io/anon/pen/BzmKqq) – Derek Story Jul 12 '16 at 06:06

1 Answers1

0

Why? Because as soon as you replace those elements in first iteration of loop...they no longer exist to be replaced in further iterations

Overall scope of what you are trying to do isn't clear without sample html provided

charlietfl
  • 170,828
  • 13
  • 121
  • 150