I have been through:
- Wrap plain text in paragraph Jquery
- Wrap text within element
- Wrap element between two elements in JavaScript/jQuery?
- jQuery wrapAll contents including text between two tags
- Get the text after span element using jquery
none of those provide a solution for what I am trying to do. I think adding the div may be part of the reason.
How can I enclose the content between div_1 and div_2 in a div_3
<div id="div_1"></div>
<strong>stuff here that always begins with same string but does not end that way</strong>
some unknown text here<br>more text<br>even more text
<div id="div_2"></div>
The real issue is that it seems you cannot insert the beginning of a div without the end of div showing up automatically.
For example, if I do something like this:
$(document).ready(function(){
$('#div_1').after('<div id="div_3">');
$('#div_2').before('</div>');
});
div_3 gets inserted after div_1 but with a closing tag i.e.
<div id="div_1"></div>
<div id="div_3"></div>
<strong>stuff here that always begins with same string but does not end that way</strong>
some unknown text here
<div id="div_2"></div>
I can get it to work but it cuts out after first <br>
using:
document.getElementById("div_1").parentNode.insertBefore(document.createElement("div"), document.getElementById("div_2")).id = "div_3";
var text_1 = document.getElementById("div_1").nextElementSibling.outerHTML + document.getElementById("div_1").nextElementSibling.nextSibling.nodeValue;
document.getElementById("div_3").innerHTML = text_1 + document.getElementById("div_1").nextSibling.innerHTML;
// Get the elements
let div1 = document.getElementById("div_1");
let div3 = document.getElementById("div_3");
// Get the content between the two divs
let content = div1.nextSibling;
// Remove the content
while (content != div3) {
content.remove();
content = div1.nextSibling;
}
Also, Shahbaz Naeem, proposed this solution before my first question was (incorrectly) tagged a duplicate
$('#div_1').nextUntil('#div_2').wrapAll('<div id="dev_3"></div>');
But same thing, it cuts out after first <br>
2
Answers
Thanks to freedomm-m's tip of
.wrapAll
I ended up with thishttps://jsfiddle.net/akmiecik/hzetk3pw/72/
First, let’s have a proof-of-concept
Explanation: the
innerHTML
is the inner HTML of the element. TheouterHTML
is the outer HTML of the element. These can be treated as strings and we can override them with strings, the result ending up being an HTML.