0

I have multiple headings with mysite.com internal links like below:

Article 1 https://externalsite1.com/url1


Article 2 https://externalsite2.com/url2


Article 3 https://externalsite3.com/url3


I need to replace all the articles internal site links to their below external sites urls

I have tried this at here: http://jsfiddle.net/n4hwjrsq/2/ but no luck, please help me

$("a").each(function() {
  var external_link = $("div.ptb_original_link").text(); 
  $(this).attr('href',$(this).attr('href').replace('',external_link)); 
});

I expect the output with externalsite links like below :

Article 1 https://externalsite1.com/url1


Article 2 https://externalsite2.com/url2


Article 3 https://externalsite3.com/url3


0

2 Answers 2

1

You need to be more specific with your external_link variable, otherwise you're just going to end up with every URL in every link:

$("a").each(function() {
  var external_link = $(this).parent().parent().next("div.ptb_original_link").text();
  $(this).attr('href', external_link);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ptb_title">
  <h2 class="entry_title"><a href="https://example.com/link1">Article 1</a></h2>
</div>
<div class="ptb_original_link">https://externalsite1.com/url1</div>
<br>
<div class="ptb_title">
  <h2 class="entry_title"><a href="https://example.com/link2">Article 2</a></h2>
</div>
<div class="ptb_original_link">https://externalsite2.com/url2</div>
<br>
<div class="ptb_title">
  <h2 class="entry_title"><a href="https://example.com/link3">Article 3</a></h2>
</div>
<div class="ptb_original_link">https://externalsite3.com/url3</div>
<br>

Sign up to request clarification or add additional context in comments.

Comments

1
$(".entry_title a").each(function() {
  $(this).attr('href',$(this).closest('div').next().html()); 
});

Or to make sure if there might be other divs before the one with external link:

$(".entry_title a").each(function() {
  $(this).attr('href',$(this).closest('div').next('.ptb_original_link').html()); 
});

Demo

Comments

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.