I’ve used the below code to dynamically wrap characters with a span.
$("span.count").children().andSelf().contents().each(function(){
if (this.nodeType == 3) {
var $this = $(this);
$this.replaceWith($this.text().replace(/(\w)/g, "<span>$&</span>"));
}
});
I am trying to (once complete) count the number of wrapped elements so I can attach a class based on the quantity to their container. I’ve tried various methods (thinking my problem is that is is trying to count dynamically created content) but none seem to work. Below is what I have so far:
var n = $("span.count").live().children().length;
if (n < 3) {
$(".counter").addClass("four");
}
Any help would be greatly appreciated.
You can’t use
.live()the way you are trying to do. It is both deprecated now and only used for delegated event handling, not for DOM changes. If you add a class to the span you’re adding, then you can simply just count it:Or, you could use a custom replacement function and increment a counter on each replacement: