window location href inside jquery replaceWith tag

1.2k Views Asked by At

thanks for the amazing community, i'm strugling with this code i'm tring to load href link with window.location.href + string '/1/' into my jquery replaceWith tag but no luck could you help me please this is my code:

var myhref=window.location.href+'/1/':
$j('.the-tag p').replaceWith('<a href="'.myhref.'">My Link</a>');

thank you for your help again

3

There are 3 best solutions below

1
A Paul On BEST ANSWER

Are you trying to do something like below ? You need to include jquery library files, and then below will work. In the code I have fixed : at the end of line 1 to ;

var myhref = window.location.href + '/1/';
$('.the-tag p').replaceWith('<a href="' + myhref + '">My Link</a>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="the-tag">
  <p></p>
</div>

0
Benjamin On

You should do this instead

var myhref = window.location.href+'/1/';
$.('.the-tag p').replaceWith('<a href="'+ myhref +'">My Link</a>');

And also you should ensure that you have the Jquery library included added in your code as well.

0
Phil On

Some problems with your current script...

  1. Your first line is terminated with : which causes a syntax error. You probably meant ;
  2. To concatenate strings in JS, you use the + operator
  3. Your script appends /1/ to the end of the complete URL. If the URL contains query parameters or fragments, this will cause problems. You should manipulate the path property only

// Show an example with a fragment location
location.hash = "#anchor"

// Clone the current URL
const myhref = new URL(location)

// Handles cases where the current path
// does or does not end in a "/"
myhref.pathname = myhref.pathname.replace(/\/?$/, "/1/")

$('.the-tag p').replaceWith($("<a>", {
  href: myhref,
  text: "My Link"
}))
/* This is just so you can see the href */
a::after {
  content: " (" attr(href) ")";
  color: grey;
  font-size: .8rem;
}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
<div class="the-tag" id="anchor">
  <p></p>
</div>