That specific example is quite easy, because the target text node is the last child in its parent; see comments:
// Create the span, give it its ID
var span = document.createElement("span");
span.id = "myspan";
// Get the div
var div = document.getElementById("myDiv");
// Move the last child of the div into the span
span.appendChild(div.childNodes[div.childNodes.length - 1]);
// Append the span to the div
div.appendChild(span);
#myspan{
color: #db1926;
}
<div id="myDiv">Here is some text of which I want the last line to be wrapped in span-tags with as id="myspan".<br>If it works this line will color red.
</div>
Or with jQuery:
// Create the span, give it its ID
var span = $("<span>").attr("id", "myspan");
// Get the div
var div = $("#myDiv");
// Move the last child of the div into the span
span.append(div.contents().last());
// Append the span to the div
div.append(span);
#myspan{
color: #db1926;
}
<div id="myDiv">Here is some text of which I want the last line to be wrapped in span-tags with as id="myspan".<br>If it works this line will color red.
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As A.Wolff points out, that can be a lot shorter using wrap:
$("#myDiv").contents().last().wrap('<span id="myspan"></span>');
#myspan{
color: #db1926;
}
<div id="myDiv">Here is some text of which I want the last line to be wrapped in span-tags with as id="myspan".<br>If it works this line will color red.
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
See:
<br>tag and then the text after it says it should be red.