2

I'm using below code for replacing links:

function replaceLink(href_array){
    $('.externalLink').each(function(index){
        $(this).replaceWith(function() {
            if ($(this).text() != "") {
                return $('<a />').append($(this).contents()).attr('href', href_array[index]);
            }
            else { // do not use
                return $('<a />').append(href_array[index]).attr('href', href_array[index]);
            }
        });
    });
};

The initial page has the following structure:

body 
    p div.externalLink /p
    p div.externalLink /p
    p div.externalLink /p
    p div.externalLink /p
    p div.externalLink /p
    p div.externalLink /p
/body

After the script, it should be:

body 
    p a#href /p
    p a#href /p
    p a#href /p
    p a#href /p
    p a#href /p
    p a#href /p
/body

But it turns out like this:

body 
    p /p a#href
    p /p a#href 
    p /p a#href
    p /p a#href
    p /p a#href
    p /p a#href
/body

How can I correct this?

at the bottom as it should be on top of how it turns out

Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43

1 Answers1

2

You are creating div tags inside p tags, which is incorrect and the opening div tag will automatically close the p tag before it, hence the replaceWith works incorrectly.

Try a div inside div.

Source - Why can't the <p> tag contain a <div> tag inside it?

var href_array = [
  "Href1", "Href2", "Href3", "Href4", "Href5", "Href6"
]

function replaceLink(href_array) {
  $('.externalLink').each(function(index) {
    $(this).replaceWith(function() {
      if ($(this).text() != "") {
        return $('<a />').append($(this).contents()).attr('href', href_array[index]);
      } else { // do not use
        return $('<a />').append(href_array[index]).attr('href', href_array[index]);
      }
    });
  });
}

replaceLink(href_array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="externalLink">A</div>
</div>
<div>
  <div class="externalLink">B</div>
</div>
<div>
  <div class="externalLink">C</div>
</div>
<div>
  <div class="externalLink">D</div>
</div>
<div>
  <div class="externalLink">E</div>
</div>
<div>
  <div class="externalLink">F</div>
</div>
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43