Reputation: 353
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>"));
});
});
Upvotes: 0
Views: 112
Reputation: 100322
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(/(\([^)]+\))/, "<span>$1</span>");
$(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>
Upvotes: 1