1

Is there a way to wrap the last line of a text in <span> tags using jQuery or Javascript?

#myspan{
  color: #db1926;
}
<div id="myDiv">Here is some text, of which I want the last line to be wrapped in span-tags with id="myspan".<br>If it works this line will color red.
</div>

4
  • From where to where do you want to be wrapped in span? Commented Dec 3, 2016 at 13:11
  • You can add the span with id where you want it to be, and then get this span with JS or JQuery, and add it your class myspan Commented Dec 3, 2016 at 13:16
  • @JayGhosh: It's clear, but only if you scroll right -- there's a <br> tag and then the text after it says it should be red. Commented Dec 3, 2016 at 13:22
  • If Crowder's answer doesn't cut it, this one does, and if so, also make this question a duplicate: stackoverflow.com/questions/37120012/… Commented Dec 3, 2016 at 13:25

1 Answer 1

4

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:

Sign up to request clarification or add additional context in comments.

1 Comment

As a side note, the jQuery sample could be simplified using $.fn.wrap() method, e.g: div.contents().last().wrap(span);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.