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
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>
Some problems with your current script...
:
which causes a syntax error. You probably meant ;
+
operator/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>
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.
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.