tags:

views:

193

answers:

2

If I have text like this;

<p>&nbsp;</p>
<p>this is the real text</p>
<p>&nbsp;</p>
<p>more</p>

What I need is a piece of jQuery that will replace the first instance only of <p>&nbsp;</p> with ''.

So the result after the call should be;

<p>this is the real text</p>
<p>&nbsp;</p>
<p>more</p>

But if the first line is not <p>&nbsp;</p> then the call should do nothing.

EDIT

I've tried implementing the solution from @Joey C. but I can't get it to work. The remove just doesn't.

var myHtml = "<p>abc</p><p>next para</p>";
var newElement = $(myHtml);

if ($(newElement).first("p").text() == "abc") {
    $(newElement).first("p").remove();
}

alert($(myHtml).text());
+8  A: 

The following finds the first instance of a p element and removes it from the DOM if it's html is equal to "&nbsp;" like you specified.

   if ($("p:first").html() == "&nbsp;")  
     $("p:first").remove();

If the html is stored as a string in a variable, myHTML, you could create a DOM element and perform a similar comparison. In testing, I discovered that it works better if you wrap the elements you are creating with a div:

  var myHtml = "<p>abc</p><p>next para</p>";
  var newElement = $("<div>" + myHtml + "</div>");

  if (newElement).find("p:first").text() == "abc") {
     newElement.find("p:first").remove();
  }

  alert(newElement.html());

This will not actually update the string containing the original html code, so you must reassign it as well if you still need it in that variable.

  myHTML = newElement.html();
Joey C.
@Joey C. what if the html is within a variable called say myHTML?
griegs
the html to check for within the p element?just compare to the variable instead:if ($("p:first").html() == myHTML)
Joey C.
No sorry, what if the html im searching in, not searching for, is inside a variable?
griegs
updated answer.
Joey C.
+1  A: 

I love jQuery (and functional programming in general) but sometimes native JavaScript is the way to go:

function ProcessParagraphs(elem)
{
    var children = elem.getElementsByTagName('p'); 

    if(children.length < 1)
        return;

    var p = children[0];

    if($(p).text().replace(/^\s+|\s+$/g,"").length != 0) //remove *all* whitespace and see if anything is left.
     return;
    else
      elem.removeChild(p); 

}

If you have list of elements to process then I'd give them a class, say 'foo', and process them with jQuery

$('.foo').each(ProcessParagraphs);
Rodrick Chapman
`getElementsByTagName()` doesn't have a leading capital.
alex
also, you declare `children` as a variable and then redeclare when you are comparing it.
alex
@alex Oops, thanks.
Rodrick Chapman