Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find text without html tag and wrapp it with a p elment

I have the following HTML code. I would like to find and replace the text without HTML tags and wrap it inside a p element using jQuery. Is there a way to reach my goal?

<div class="col span_12_of_12 firstDiv">
  <h2>My tasks</h2>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr
  <ul>
    <li>Lorem ipsum dolor sit</li>
    <li>Lorem ipsum dolor sit</li>
    <li>Lorem ipsum dolor sit</li>
    <li>Lorem ipsum dolor sit</li>
  </ul>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr
</div>
like image 652
Daniel Avatar asked Apr 26 '17 13:04

Daniel


People also ask

How do I find text in HTML?

The <input type="search"> defines a text field for entering a search string. Note: Remember to set a name for the search field, otherwise nothing will be submitted. The most common name for search inputs is q.

Can I use div for text?

This allows all kinds of readers to interpret your content more thoroughly. So while from a technical point of view text is absolutely valid in bare <div> elements (which don't contain any semantical meaning), from a content's point of view you absolutely should use <p> elements when displaying text on your site.

What is the difference between div and P in HTML?

DIV is a generic block level container that can contain any other block or inline elements, including other DIV elements, whereas P is to wrap paragraphs (text).


1 Answers

To achieve this you need to find the child textNodes and wrap them in a <p> tag. To do that you can use contents() and filter() then wrap(), like this:

$('.col').contents().filter(function() {
  return this.nodeType == 3 && this.textContent.trim();
}).wrap('<p />');
p { border: 1px solid #C00; } /* only used to make the output obvious */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col span_12_of_12 firstDiv">
  <h2>My tasks</h2>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr
  <ul>
    <li>Lorem ipsum dolor sit</li>
    <li>Lorem ipsum dolor sit</li>
    <li>Lorem ipsum dolor sit</li>
    <li>Lorem ipsum dolor sit</li>
  </ul>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr
</div>
like image 50
Rory McCrossan Avatar answered Nov 14 '22 20:11

Rory McCrossan