Fading in char by char (keeping DOM intact)
<p>I want to animate a text so that it fades in character by character. I actually managed to do this without keeping the DOM intact and it looks like this:</p>

<pre><code>// make each character an own span element
// abc will become &lt;span&gt;a&lt;/span&gt;&lt;span&gt;b&lt;/span&gt;&lt;span&gt;c&lt;/span&gt;
var elements = $(elemId).text().split('');
$(elemId).text('');

for (var i = 0; i &lt; elements.length; i++) {
    $(elemId).append('&lt;span&gt;' + elements[i] + '&lt;/span&gt;');
}

// fade in all spans one by one
$(elemId + " span").each(function(index) {
    $(this).delay(speed * index).fadeIn(300);
});
</code></pre>

<p>But this breaks possible elements within my text, especially strong, but also lists or tables. So I thought about these two possible solutions:</p>

<ul>
<li>Traverse the DOM with jQuery and wrap each character with a <code>&lt;span&gt;</code>, but do not delete the other elements. Then we still have the problem, that the table rows will always be displayed (just empty)</li>
<li>Traverse the DOM with jQuery and wrap each character with a <code>&lt;span&gt;</code> and disable each other element to <code>display: none</code>. Then retraverse it and show stuff as it comes along (both <code>span</code> and other elements). This might break HTML for a while (<code>&lt;ul&gt;</code> without <code>&lt;li&gt;</code> inside etc., but I guess all browsers will be able to handle it well enough).</li>
</ul>

<p>I started with <code>contents()</code> method, but I did not really get on.</p>

<p>This is what I currently have, but it does not replace anything at all (even though it finds some text at least):</p>

<pre><code>$(elemId).contents().each(function() {
    if (this.nodeType == 3) {
        var elements = $(this).text().split('');
        alert(elements);
        // does not delete anything, but it would also break 
        // if it deleted something
        // because text('') goes over elements like &lt;strong&gt; etc.
        $(this).text('');
        alert($(this).text());

        for (var i = 0; i &lt; elements.length; i++) {
            $(this).append('&lt;span&gt;' + elements[i] + '&lt;/span&gt;');
        }
    }
});
</code></pre>

<p>So what do I have to do to get my text and tags correctly? If everything is set up like above, I guess it’s just a matter of using <code>contents()</code> recursively and set visibility on all elements again. But adding my <code>&lt;span&gt;</code> properly seems difficult.</p>

<h2>Some example</h2>

<pre><code>I am &lt;strong&gt;AB&lt;/strong&gt;
</code></pre>

<p>Should become:</p>

<pre><code>&lt;span display="none"&gt;I&lt;/span&gt;&lt;span display="none"&gt; &lt;/span&gt;
&lt;span ...&gt;a&lt;/span&gt;&lt;span ...&gt;m&lt;/span&gt;&lt;span ...&gt; &lt;/span&gt;
&lt;strong ...&gt;&lt;span ...&gt;A&lt;/span&gt;&lt;span ...&gt;B&lt;/span&gt;&lt;/strong&gt;
</code></pre>
