Eupatoria
Eupatoria

Reputation: 130

jQuery: how do I replace part of original hyperlink with non-hyperlinked text?

I have a class, let's say .check-status, that is a text that has a hyperlink in it.

I have an event listener on click that is supposed to replace that text with a variable statusResponse and then say 'Check again'. So it would say something like 'Your status is pending. Check again'; but 'Check again' needs to be the original hyperlink and 'Your status is pending' should be regular text.

I know how to use something like the below:

$('.check-status').text(statusResponse).append(' Check again')

But that gives me everything as a hyperlink, and I only want the 'Check again' part to be that hyperlink.

How do I achieve that without creating new divs, etc?

Thanks!

Upvotes: 0

Views: 43

Answers (2)

AGE
AGE

Reputation: 3792

var statusResponse = "Your status is pending.",
    customFlag = false;

$(".custom-btn").click(function(){
    if(!customFlag){
        customFlag = true;
        var checkStatus = $(".check-status");
        checkStatus.before(statusResponse + " ").text("Check again");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="custom-btn">Click me</button>
<br/><br/>
<a class="check-status" href="#">Check your status.</a>

So what does this do?

  1. First of all since we are reusing $(".check-status") so often it is preferable to have it in a var named checkStatus.
  2. Using before we take the text inside checkStatus and put it before and outside checkStatus.
  3. The text that sits inside statusResponse is now placed inside the checkStatus object.
  4. We only want this to occur once, so a flag is required.

Upvotes: 1

trincot
trincot

Reputation: 350781

As you want the hyperlink to only be on a part of the complete text, you'll need an anchor element only for that text, while the complete text should be formatted with your class. So proceed like this:

HTML

<span class="check-status"><a href="status.php" >Your status is pending</a></span>

JavaScript

var statusResponse = "Your status is pending. ";
var checkAgain = "Check again."
$('.check-status>a').before(statusResponse).text(checkAgain);

Here is fiddle as demo.

Upvotes: 2

Related Questions