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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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():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:
Working demo: http://jsfiddle.net/9AXvN/1/