Here is my HTML “sandbox”:
<p>1 2 3</p>
<span id="myid">
<span id="mytext">
<p>4 5 6</p>
<p>7 8 9</p>
<p>10 11 12</p>
</span>
</span>
<p>13 14 15</p>
I would like to “merge” the p tags accordingly:
(To make it easier to see I’ve added a minus sign where I’ve made the changes:)
<p>1 2 3 -
<span id="myid">
<span id="mytext">
- 4 5 6</p>
<p>7 8 9</p>
<p>10 11 12 -
</span>
</span>
- 13 14 15</p>
Every place I’ve added a minus sign, I have actually stripped a <p> or </p> tag making a merge between the two paragraph elements ( between 1 2 3 and 4 5 6 & between 10 11 12 and 13 14 15) – (This merge is only to achieve a display inline for 123-456 & 101112-131415).
How can I achieve this result with ‘raw’ JavaScript (not libraries please).
Note:
I’ve tried to create something but It took me 80 lines of code – I am sure there is a better way of doing this.
Edit:
Jon Hanna mentioned in his comment I could use correct HTML like so (as the result of JavaScript):
<p>1 2 3 <span class="myclass mytext">4 5 6</span></p>
<p class="myclass mytext">7 8 9</p>
<p><span class="myclass mytext"10 11 12</span> 13 14 15</p>
(Bear with me, I started writing this before your latest edit. I think it’s still useful, though.)
I’m not sure what you want to achieve, but I can tell you that it’s very hard to achieve exactly what you’re asking for using JavaScript. This is mostly because the HTML would be invalid.
Let’s first walk through why the HTML would be invalid. When the browser parses HTML, it builds a nested tree of DOM Nodes. Your first example could be represented like this:
<p><span id="myid"><span id="mytext"><p><p><p><p>Using JavaScript and the DOM, you can walk through this tree and manipulate it. You could combine the text node from various
<p>tags and place them in a single<p>tag without problem. But you won’t be able to create the structure of your second example. It’s simply not shaped like a DOM tree, so you can’t use the DOM to create that HTML.The only way manipulate the HTML into the shape of your second example is through
innerHTML, like Jon Hanna explains. The good news is that browsers will always correct invalid HTML into a valid DOM structure. The bad news is that each browser does this differently, so you never know what you end up with.The only real solution is to rethink your HTML structure, like you’ve done in your latest edit.
The way to solve your original problem depends on how static your original HTML is. I’ll give a crude example, for which I’ll presume that:
<p>‘s<p>‘s are always inside the<span>‘s, and the first and fifth always outside themIf those two conditions are met, you could use something like this:
I’ve posted a working example on JSFiddle: jsfiddle.net/vSrLJ/