Insert <span> in <p> element
Solution 1
Try this
var txt = "Hello bye";
var dataArr = txt.split(' ');
var paragraph = document.getElementById("pid");
paragraph.innerHTML = dataArr[0]+ " <span>"+dataArr[1]+"</span>";
Here is a demo
Solution 2
It's possible (the following assumes the p
has an ID, like you said), in it's simplest form you can just do:
var paragraph = document.getElementById("pId");
paragraph.innerHTML = "Hello <span>World</span>";
Or if you want to use jQuery:
$("#pId").html("Hello <span>World</span>");
Or (as you said in comments, you want to keep the existing content, but wrap the last word in a span
, you can do:
var newHTML = $("#pId").html().replace(" ", " <span>");
$("#pId").html(newHTML).append("</span>");
Solution 3
I would like to share a jQuery solution, which is regardless of any words defined in your p
element
$("p").html(function(){
var mystring= $(this).text().split(" ");
var lastword = mystring.pop();
return mystring.join(" ")+ (mystring.length > 0 ? " <span>"+ lastword + "</span>" : lastword);
});
In the demo above, I am splitting the string first, than am using pop
to get the last index in the array, and than am adding span
element and returning the string using join
Anoniem Anoniem
Updated on July 20, 2022Comments
-
Anoniem Anoniem almost 2 years
I got like;
<p>Variable Text</p>
And I want to it to be;
<p>Variable <span>Text</span></p>
Is this possible by a javascript function? / or jQuery.
Oh yeah, and the p-element got an ID and the text inside the p-element is variable but always consists of 2 words. I want a span around the last word of the text by a javascript function.
-
Anoniem Anoniem over 10 yearsjQuery / Javascript, doesn't really matter to me. As long as it works ..
-
iJade over 10 years@AnoniemAnoniem posted a new answer
-
-
mattytommo over 10 years@Downvoter Care to comment? Is it because I didn't use jQuery? Wake up and smell the coffee, there is JavaScript outside of the world of jQuery.
-
Anoniem Anoniem over 10 yearsBut the text inside the <p> is variable and always consists of two words. I want the <span> around the last (second) word (the one after the whitespace) in it.
-
Anoniem Anoniem over 10 yearsBut the text inside the <p> is variable and always consists of two words. I want the <span> around the last (second) word in it.
-
Anoniem Anoniem over 10 yearsUncaught TypeError: Object <span> has no method 'append' ?
-
mattytommo over 10 years@AnoniemAnoniem Try now :)
-
iJade over 10 yearsglad it helped...And don't forget to upvote or mark as answer ;)
-
Anoniem Anoniem over 10 yearsI had to wait before I was able to mark it as answer, you were too quick!