Gareth Gillman Gareth Gillman - 1 month ago 13
jQuery Question

Replace each element in a list with jQuery

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>"));
});
});

Answer

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>

Comments