How to Wrap Each Word of an Element in a Span Tag

How to wrap each word of an element in a span tag?

It's gonna be a little more complicated than that. You're gonna have to find out all the words and re-append them to your element, wrapped in a span.

var words = $("p").text().split(" ");
$("p").empty();
$.each(words, function(i, v) {
$("p").append($("<span>").text(v));
});

Live example

How to wrap each word in a span

Something like this?

const text = "These are some words for a test";

text.split(' ').forEach(word => { // loop over every word
const element = document.createElement("span"); // create element "span"
element.innerText = word; // set its content to word
element.onclick = () => // onclick handler
element.style.background = '#000'; // action
document.body.appendChild(element); // add element to dom
});
span {
color: orange;
margin-left: 3px;
}

Wrap all individual words in a span tag based on their first letter

What you're trying to achieve can't be done with regex if you want to reference the individual words.

I've wrote a little snippet that uses document.querySelector() instead

outerText property on the query selector object returns a plain text string which is later converted to an array with split() function

Then it simply loops over the array and appends the style tag and to get the first letter I've used substring() function

const words = document.querySelector("#words").outerText.split(" ");
const wordsDiv = document.querySelector("#words")

wordsDiv.innerHTML = ""
words.map((el) => {
wordsDiv.innerHTML += `<span class="${el.substring(0, 1)}">${el}</span> `
})
<div id="words">red green blue orange</div>

Wrap each word of a html content in a span

try

$('p')
.find('*')
.addBack('p')
.each(function () {

textNode = $(this).contents().filter(function () {
return this.nodeType === 3; //Node.TEXT_NODE
});

text = textNode.text().split(' ');
replace = '';

$.each(text, function (index, value) {
if ( value.replace(/\s+/, "") ) { // Remove whitespaces
replace += '<span class="wraped">' + value + '</span>';
}
});

textNode.replaceWith( $(replace) );

});

JSFiddle

How to wrap each letter in a span and keep normal word breaks and subelements

I've made an solution that also wraps each word into a span. This way wrapping still works on whole words.

Also (1 level) of sub-elements is preserved in the end result. For example:

a <strong>bc</strong> d

Is converted into:

<span class="word">
<span class="letter">a</span>
</span>
<span class="word">
<span class="letter">
<strong>b</strong>
</span>
<span class="letter">
<strong>c</strong>
</span>
</span>
<span class="word">
<span class="letter">d</span>
</span>

Known issues:

  • Only one level of sub-elements works (So <p>Hello <strong><u>W</u>orld</strong></p> won't)
  • Text against another element create two separate words (So <p>User<strong>name</strong></p> are two words)

The full solution:

$.fn.convertToSeperateLetters = function() {
return this.each(function() {
var $el = $(this);
var elements = convertToSeperateLetters($el, false);

$el.empty().append(elements);

return $el;
});
}

$('p').convertToSeperateLetters();

function convertToSeperateLetters($element, asSubNode) {
var elements = [];

var childNodes = $element.contents();

// Loop through all child nodes of selected element
for (var c = 0; c < childNodes.length; c++) {
var node = childNodes[c];
var type = node.nodeType;

// Process a child element
if (type == Node.ELEMENT_NODE) {
Array.prototype.push.apply(elements, convertToSeperateLetters($(node), true));
}

// Process a piece of text
else if (type == Node.TEXT_NODE) {
var text = node.nodeValue;

// Process each word
var words = text.split(' ');
for (var w = 0; w < words.length; w++) {
var word = words[w];

// Skip empty words
if (word == '') continue;

// Wrap each word into span
var $word = $('<span/>').addClass('word');
for (var l = 0; l < word.length; l++) {
var letter = word[l];

// Wrap each letter into span
var $letter = $('<span/>').addClass('letter');

if (!asSubNode) {
$letter.html(letter);
}

if (asSubNode) {
var $subNode = $element.clone().empty().html(letter);
$letter.append($subNode);
}

$word.append($letter);
}

elements.push($word);
}
}
}
return elements;
}
p,
.word,
.letter {
padding: 3px 1px;
}

p {
border: 1px solid red;
}

.word {
display: inline-block;
border: 1px solid green;
margin-left: 2px;
margin-right: 2px;
}

.letter {
display: inline-block;
border: 1px solid blue;
}

.word-wrapped {
width: 360px;
background: lightgrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Hello World</p>
<p>Hello <strong>World</strong></p>

<div class="word-wrapped">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p>
</div>

Wrap each first letter of each word in span tag - javascript

This seems to work for me, may be a bit clumsy though

$(document).ready(function()
{
// For each of the eachword class
$("a.eachword").each(function()
{
// Get the string (html) and split it by " " (like PHP's explode)
var self = $(this);
var theText = self.html();
var theTextArray = theText.split(" ");

// Cycle them
for (var i = 0; i < theTextArray.length; i++)
{
// Get this particular word and split it into individual letters
var thisWord = theTextArray[i];
var thisWordArray = thisWord.split("");

// Wrap the first letter if it is not a HTML char code
if (thisWordArray[0] != "&")
{
thisWordArray[0] = "<span class='firstletter'>"+thisWordArray[0]+"</span>";
}

// Stitch the letters back up
theTextArray[i] = thisWordArray.join("");
}

// Join the original string back up
var result = theTextArray.join(" ");

self.html( result );
});
});

http://jsfiddle.net/SFgXZ/

How to Wrap text in span and not breaking words?

Each inline-block is treated as its own word. To make words stick together you could wrap each word in another span for example like this:

$('.text').each((i, e) => {
const element = $(e);
element.html(element.text().split(' ').map(word => {
const letters = (word + ' ').split('').map(char => '<span>' + char + '</span>');
return '<span class="word">' + letters.join('') + '</span>';
}).join(''));
});
.text .word {
display: inline-block;
}

Or, if all you need are just spaces between letters, you can achieve it using letter-spacing and word-spacing

How to wrap array of html span tags with more span tags?

Change text into an array of strings. Then loop over the words and split them into characters:

export default function Header({ words = ["hello", "world"] }) {
const header = words.map((word, j) => {
return (
<>
<span>
{word.split("").map((letter, i) => {
const colours = [
"red",
"green",
"yellow",
"blue",
"pink",
"orange",
];
const rng = Math.floor(Math.random() * colours.length);

return (
<span key={i} style={{ color: colours[rng] }}>
{letter}
</span>
);
})}
</span>
{j < words.length - 1 && <span className="white-space"></span>}
</>
);
});

return <h1 id="header">{header}</h1>;
}


Related Topics



Leave a reply



Submit