user2417624
user2417624

Reputation: 683

How to add html tags before and after certain string using jquery

I have the following HTML:

<h5 class="pi-accordion-title">
    <a href="#" class="z">
        <span class="pi-accordion-toggle"></span>
            My Link (Keyword)
    </a>
</h5>

which is part of an accordion link. What I am trying to do is to open span tag before the (Keyword) and close it after that.

I am trying with the following JAVASCRIPT:

<script>
    $("(Keyword)").before("<span class='orange'>"); 
    $("(Keyword)").after("</span>");         
</script>

but it doesn't work...Console log show the following error:Syntax error, unrecognized expression: (Keyword)

Upvotes: 1

Views: 1779

Answers (3)

Quentin Roy
Quentin Roy

Reputation: 7887

You cannot select text like this with jQuery. Here is a very simple way to do it which does not even need jQuery.

The drawback of this approach is that the entire content of the container is re-written, which means that if you want to attach event to some children of the container, you have to do it after you inserted the spans. As a result, I would recommend to choose a container as small as possible.

var toReplace = '(Keyword)'; var containers = document.getElementsByClassName("pi-accordion-title"); Array.prototype.forEach.call(containers, function(container){ container.innerHTML = container.innerHTML.replace(toReplace, '$&'); });

.pi-accordion-title a span {
  color:red;
}
<h5 class="pi-accordion-title">
    <a href="#" class="z">
        <span class="pi-accordion-toggle"></span>
            My Link (Keyword)
    </a>
</h5>

EDIT

If you want to avoid the aforementioned element overwriting drawback, you can leverage the ":contains" jQuery selector. If you are using jQuery I actually think it is the best/safest method as you will only re-write the parent elements.

var toReplace = '(Keyword)';
$(":contains(" + toReplace + ")").each(function(){
  this.innerHTML = this.innerHTML.replace(toReplace, '<span>$&</span>');
});
.pi-accordion-title a span {
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h5 class="pi-accordion-title">
    <a href="#" class="z">
        <span class="pi-accordion-toggle"></span>
            My Link (Keyword)
    </a>
</h5>

Upvotes: 1

Jack jdeoel
Jack jdeoel

Reputation: 4584

I have tried with jquery.Grab the class name and get the text or html ,then you can replace by .replace with find word

var title = $(".pi-accordion-title");
var text = title.html();
title.html(text.replace(/(\(Keyword\))/g,"<span class='orange'>$&</span>"));

Upvotes: 0

Deep
Deep

Reputation: 2512

$('.pi-accordion-title').each(function() {
    this.innerHTML = this.innerHTML.replace(/(\(Keyword\))/, '<span class="orange">$1</span>');
});

Upvotes: 1

Related Questions