How can I select the first word in a div?
I need to be able to insert a line break after the first word, or wrap it in a span tag. I need to do this for multiple divs on a page with the same class.
The ::first-letter selector is used to add a style to the first letter of the specified selector. Note: The following properties can be used with ::first-letter: font properties. color properties.
Solutions with CSS and HTML If you want to change the color of the first word of a text, you can use the CSS :before pseudo-element, which is used to add any element. Its value is defined with the content property. If it is not used, the content will not be generated and inserted.
The ::first-letter pseudo-element represents the first letter of an element, if it is not preceded by any other content (such as images or inline tables) on its line.
Replacing HTML will result in event handlers being unbound and replacing the entire text for an element will result in HTML markup being lost. The best approach leaves any HTML untouched, manipulating only the first text node of the matching element. To get that text node, you can use .contents()
and .filter()
:
function wrapFirstWord () {
// Select only the first text node
var node = $("div").contents().filter(function () {
return this.nodeType == 3;
}).first(),
// Get the text...
text = node.text(),
// ... and the first word
first = text.slice(0, text.indexOf(" "));
if (!node.length)
return;
// Remove the first word from the text
node[0].nodeValue = text.slice(first.length);
// Add it back in with HTML around it
node.before('<span>' + first + '</span><br/>');
};
Working demo: http://jsfiddle.net/9AXvN/
Using this method will ensure that manipulating the first word will have no unwanted side effects on the rest of the element's content.
You can easily tack this on as an extension to jQuery, with an optional value for the number of words you want to wrap:
$.fn.wrapStart = function (numWords) {
var node = this.contents().filter(function () {
return this.nodeType == 3
}).first(),
text = node.text(),
first = text.split(" ", numWords).join(" ");
if (!node.length)
return;
node[0].nodeValue = text.slice(first.length);
node.before('<span>' + first + '</span><br/>');
};
Working demo: http://jsfiddle.net/9AXvN/1/
This should work:
$('div.message').each(function() {
var html = $(this).html();
var word = html.substr(0, html.indexOf(" "));
var rest = html.substr(html.indexOf(" "));
$(this).html(rest).prepend($("<span/>").html(word).addClass("em"));
});
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With