0

Trying to replace (x) in a list element with <span>(x)</span> but i can't get it right, it's duplicating the first element

my code is:

jQuery(document).ready(function($){
 "use strict";
 $(".widget_categories li").each(function(){  
  $(this).html($(".widget_categories li").html().replace(/(\([^)]+\))/, "<span>$1</span>"));
 });
});
0

1 Answer 1

1

You probably want to get the single element, not all of them again when you try to replace the html. So instead of

$(this).html($(".widget_categories li").html().replace(/(\([^)]+\))/, "<span>$1</span>"));

Change to

$(this).html($(this).html().replace(/(\([^)]+\))/, "<span>$1</span>"));

Example (note I escaped the span tag just to make it easier to see the result)

$(function(){
  $(".widget_categories li").each(function () {
    var newValue = $(this).html().replace(/(\([^)]+\))/, "&lt;span&gt;$1&lt;/span&gt;");
    $(this).html(newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="widget_categories">
  <li>foo (x) bar</li>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.