1

I'm using a plugin that is generating some additional markup that needs to be removed. I can detect if the HTML entity   exists in a specific element, but I cannot seem to change it using html().

Can anyone spot the issue that's preventing the element from being changed?

HTML

<div class="quote">
    <blockquote>John Doe wrote:
        <p></p>
        <blockquote>
            <p>Jane Doe wrote: This is awesome!</p>
        </blockquote>
    </blockquote>
    <p>&nbsp;</p>
</div>

jQuery

if ($('.quote').find('p:contains("&nbsp;")')) {
  console.log('&nbsp; detected');
  $('.quote').find('p:contains("&nbsp;")').html("inserted text");
}

Here's my fiddle.

Cofey
  • 11,144
  • 16
  • 52
  • 74
  • 1
    You aren't really detecting it. `if ($('.quote').find('p:contains(" ")'))` will always return true; it will always return an array. You should be checking the length of the array instead: `if ($('.quote').find('p:contains(" ")').length > 0)`. – Malk Feb 06 '15 at 18:38
  • http://stackoverflow.com/questions/5237989/nonbreaking-space You need the javascript representation of a non-breaking space (`\xA0`), not the html entity. – James Montagne Feb 06 '15 at 18:43
  • **Note to the OP :** The if is totally useless there.... – Karl-André Gagnon Feb 06 '15 at 18:50

3 Answers3

4

Use \xA0 for &nbsp;:

if ($('.quote').find('p:contains("\xA0")').length) {//use length to verify if it exist
  console.log('&nbsp; detected');
  $('.quote').find('p:contains("\xA0")').html("inserted text");
}

working fiddle

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
3

This gets rid of the find and the extra call to $('.quote'):

$('.quote p:contains(\xA0)').html('inserted text');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quote">
    <blockquote>John Doe wrote:
        <p></p>
        <blockquote>
            <p>Jane Doe wrote: This is awesome!</p>
        </blockquote>
    </blockquote>
    <p>&nbsp;</p>
</div>
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
-2

Your if condition is actually invalid. A jQuery selector will always return a jQuery object, so the if will always be true whether or not the DOM element is found. If you want to check for actual results from .find(...) always use .length. ie: if ($('.quote').find('p:contains("&nbsp;")').length).

Beyond this, your use of contains is incorrect as contains looks for DOM elements and not content.

To achieve what you're looking for, off the top of my head, you should find all p elements, then iterate over them and manually compare $p.html() against &nbsp;

dshapiro
  • 376
  • 2
  • 12