2

I saw this:

$("div").children().andSelf().contents().each(function(){
    if (this.nodeType == 3) {
        var $this = $(this);
        $this.replaceWith($this.text().replace(/(\w)/g, "<span>$&</span>"));
    }
});

here: wrap each char in except tags with jQuery

Now i try to give each span a id, but they end up all having the same id. The index that get's logged to the console however are different.

$("#content").children().andSelf().contents().each(function(index){
    console.log(index);
        if (this.nodeType == 3) {
            var $this = $(this);
            $this.replaceWith($this.text().replace(/(\w)/g, "<span id="+index+">$&</span>"));
        }
    });
Community
  • 1
  • 1
clankill3r
  • 9,146
  • 20
  • 70
  • 126
  • Well, you are replacing each character on one text node with the same `"$&"` string. The `index` for each text node will be different though. – Felix Kling Jan 08 '12 at 21:18
  • In your log, are you seeing what is expected? have you tried doing console.log(this.noteType), or console.log($this)? Add more traces, it should help with the debugging process. [Side note: to change the id of an element, you can just do $this.prop("id",index)] – BananaNeil Jan 08 '12 at 21:21
  • I tested with "logo" so it logged 1, 2, 3, 4 but it didn't occur to me that that where the elements. Anyway how can i solve this? Also i don't understand the values it logs, the div #content only contains 1 paragraph. – clankill3r Jan 08 '12 at 21:25
  • console.log(this.noteType) logs 3. console.log($this) logs strange stuff like [" ] " – clankill3r Jan 08 '12 at 21:31

1 Answers1

0

This answer might be of use to you.

If you want each letter in a span, an an unique id for each one, here's how it could be done:

$("#content").children().andSelf().contents().each(function(index){
    if (this.nodeType == 3) {
        var $this = $(this);
        $this.replaceWith($this.text().replace(/\w/g, function(text,index2) {
            return "<span id="+index+""+index2+">" + text + "</span>";
        }));
    }
});

Obs.: I'm not sure every browser support this form of Regex.replace. Tested with FF3.6 and Chrome.

Clarifying a bit: This form is new to me too, just learned today, but couldn't find relevant documentation online. It appears that, for a regex without capturing groups, the first argument is the matched text and the second it's index in the original string. Otherwise, the second argument becomes the first captured group, and I assume the 3rd is the 2nd c.g. and so on... If anyone know where to find more info, I'm interested in it too.

Community
  • 1
  • 1
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112