TransWikia.com

Better way to wrap specific Word of div?

Stack Overflow Asked on November 20, 2021

I’m trying to simply turn the word ‘login’ from "Please login to comment" into a hyperlink, with the URL being the href from .wpd-login.

I’ve got it technically working but JSFiddle is acting like this is incorrect syntax. is there a better way to do this task?

var URL = 'https://example.com/?s_login_popup';

$(".wpd-login-to-comment").each(function() {
  //$(this).html($(this).html().replace(/login/g, "<strong>login</strong>"));
  $(this).html($(this).html().replace(/login/g, "<a href="
    ' + URL + '
    ">login</strong>"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpd-login-to-comment">Please login to comment</div>

<div class="wpd-login">
  <a href="https://example.com/?s_login_popup"><i class="fas fa-sign-in-alt"></i> Login</a> </div>

2 Answers

var URL = 'https://example.com/?s_login_popup';

$(".wpd-login-to-comment").each(function() {
    //$(this).html($(this).html().replace(/login/g, "<strong>login</strong>"));
    $(this).html($(this).html().replace(/login/g, "<a href="+ URL +">login</strong>"));
});
<div class="wpd-login-to-comment">Please login to comment</div>
<div class="wpd-login">
    <a href="https://example.com/?s_login_popup">
    <i class="fas fa-sign-in-alt"></i> Login</a>            
</div>    
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Answered by CodeBug on November 20, 2021

Make one minor change:

var URL = 'https://example.com/?s_login_popup';
$(".wpd-login-to-comment").each(function(i, el) {
  $(el).html($(el).text().replace(/login/g, "<a href='" + URL + "'>login</a>"));
});

Since you're using " to build your HTML String, you need to ensure they are being used properly.

Example: https://jsfiddle.net/Twisty/hc5dvmk3/4/

Answered by Twisty on November 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP