chap
chap

Reputation: 1869

How to wrap text with an element where you don't have control over markup?

So I'm working on a feature where I don't have control over the markup. I want to add padding to some text but the problem is that it doesn't have a container element that I can target. If I target the .content-header and add padding it pads all the content within that div which is not what I want. Markup looks like this. How can I wrap the text with a <p> element?

<div class="content-header">
  <div class="element"><img src="img.png"></div>
  "Text that I want to wrap in an element"
</div>

Upvotes: 1

Views: 126

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173532

You can use .contents() to get all nodes; then, filter the non-empty text nodes and wrap that:

$('.content-header')
  .contents()
  .filter(function() {
    // we're only interested in text nodes that are not empty
    return this.nodeType == 3 && $.trim(this.nodeValue).length;
  })
  .wrap('<p>');

Demo

Upvotes: 1

MaxZoom
MaxZoom

Reputation: 7743

You can just filter a text (nodeType=3) and then wrap it in a p tag. See below:

$('.content-header').contents().filter(function(){
   return this.nodeType === 3;
}).wrapAll("<p class='red' />");
.red { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-header">
  <div class="element"><img src="https://i.sstatic.net/6UgUs.jpg?s=32&g=1"></div>
  "Text that I want to wrap in an element"
  <span>Another text in span</span>
</div>

Upvotes: 0

Related Questions