peace_love
peace_love

Reputation: 6461

How can I find text that is not inside a div element?

I try to find text that is not inside a div element and wrap it into a div:

$( ".details" ).text().wrap( "<div></div>" );
.details div {
    font-size: 11px;
    color: #777;
    letter-spacing: 1px;
    text-transform: uppercase;
    padding: 4px 0;
    margin: 0;
    border-top: 1px solid rgba(0,0,0, .05);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="details">
    <div>monkey</div>   
    elephant
    <div>rabbit</div>   
    <div>sun</div>  
    <div>moon</div> 
    <div>bird</div>                                                          
 </div>

I cannot find the right way to to this.

The result I try to achieve is:

<div class="details">
    <div>monkey</div>   
    <div>elephant</div>
    <div>rabbit</div>   
    <div>sun</div>  
    <div>moon</div> 
    <div>bird</div>                                                          
 </div>

Upvotes: 1

Views: 115

Answers (2)

Dan Mullin
Dan Mullin

Reputation: 4435

Just turn your text into an array and wrap each element individually.


    var text = $( ".details" ).text().split(" ");
    for (var i = 0; i < text.length; i++) {
        text[i] = "<div>" + text[i] + "</div>";
    }

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337550

To achieve this you can retrieve the child text nodes using a combination of contents() and filter(). Then you can surround them in a div using wrap():

$('.details')
  .contents()
  .filter((i, node) => node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '')
  .wrap('<div />');
.details div {
  font-size: 11px;
  color: #777;
  letter-spacing: 1px;
  text-transform: uppercase;
  padding: 4px 0;
  margin: 0;
  border-top: 1px solid rgba(0, 0, 0, .05);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="details">
  <div>monkey</div>
  elephant
  <div>rabbit</div>
  <div>sun</div>
  <div>moon</div>
  <div>bird</div>
</div>

Upvotes: 4

Related Questions