Gareth Gillman Gareth Gillman - 1 year ago 100
jQuery Question

Replace each element in a list with jQuery

Trying to replace (x) in a list element with

but i can't get it right, it's duplicating the first element

my code is:

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

Answer Source

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)

  $(".widget_categories li").each(function () {
    var newValue = $(this).html().replace(/(\([^)]+\))/, "&lt;span&gt;$1&lt;/span&gt;");
<script src=""></script>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download