Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap text within element

Tags:

jquery

I need to wrap text inside a div with a span.

<div class="item">
   <span class="count"></span>
   Text that needs to be wrapped.
</div>

<div class="item">
   <span class="count"></span>
   Text that needs to be wrapped.
</div>

<div class="item">
   <span class="count"></span>
   Text that needs to be wrapped.
</div>

Tried this but it did not really work...

$('.item').text().wrap('<span class="new" />'); 
like image 414
santa Avatar asked Nov 30 '12 19:11

santa


People also ask

How do I wrap text in a div?

If you've faced the situation when you need to wrap words in a <div>, you can use the white-space property with the "pre-wrap" value to preserve whitespace by the browser and wrap the text when necessary and on line breaks. Also, you'll need the word-wrap property.

How do I wrap text in next line in CSS?

The overflow-wrap property in CSS allows you to specify that the browser can break a line of text inside the targeted element onto multiple lines in an otherwise unbreakable place. This helps to avoid an unusually long string of text causing layout problems due to overflow.

Can we wrap text in input field?

You can't wrap text in a text input box, so perhaps you should use a textarea.

What is the use of wrap in HTML?

HTML wrap Attribute Previous All HTML Attributes. Definition and Usage. The wrap attribute specifies how the text in a text area is to be wrapped when submitted in a form. Applies to. The wrap attribute can be used on the following element: Element Attribute <textarea>

How do you wrap text in CSS?

How CSS Text Wrap Works. CSS handles stretched long words using the inbuilt word-wrap or overflow-wrap property. However, when not controlled, browsers handle such long texts by default. They won't wrap long words until they receive the instruction to do so.

What is the wrap attribute?

Definition and Usage The wrap attribute specifies how the text in a text area is to be wrapped when submitted in a form.

Why do I need to wrap text around my content section?

Even if you control what goes into your content section, users can post links or other words that don't fit into your text container or your entire DOM. Therefore, applying text wrap to such a section is necessary to keep the DOM intact. Want to make your website look amazing on mobile devices?


2 Answers

You can do it using contents() and .eq()

$('.item').each(function(i, v) {
    $(v).contents().eq(2).wrap('<span class="new"/>')
});​

http://jsfiddle.net/qUUbW/

like image 119
wirey00 Avatar answered Sep 21 '22 15:09

wirey00


How about

$('.item').contents().filter(function(){
    return this.nodeType == 3 && $.trim(this.nodeValue).length;
}).wrap('<span class="new" />');

http://jsfiddle.net/mowglisanu/x5eFp/3/

like image 29
Musa Avatar answered Sep 24 '22 15:09

Musa