I’m just getting started with Javascript and am struggling to find a way to:
- Find one or more consecutive elements of the same type, e.g.
<p>…</p>or<p>…</p><p>…</p> - Surround each group with a new element, e.g.
<dd><p>…</p></dd>or<dd><p>…</p><p>…</p></dd>
I’d also like to limit the script so that it applies only to a particular part of the page, e.g. <div id="relevantbit"></div>, but perhaps that counts as a separate question.
Thanks in advance for any help.
Here’s is a native javascript function that will wrap consecutive tags at the same level in whatever type of tag you want it wrapped in. It even works recursively so it will find them to any level. As written, when detecting consecutive tags, it ignores non-elements such as text nodes or comment nodes, but it could easily be modified if that was not the desired behavior (that detail wasn’t specified).
You can see a working demo here: http://jsfiddle.net/jfriend00/Bp97p/.
And here’s the code: