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?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.