If I have text like this;
<p> </p>
<p>this is the real text</p>
<p> </p>
<p>more</p>
What I need is a piece of jQuery that will replace the first instance only of <p> </p>
with ''.
So the result after the call should be;
<p>this is the real text</p>
<p> </p>
<p>more</p>
But if the first line is not <p> </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());
Use the replace() method to replace the first occurrence of a character in a string. The method takes a regular expression and a replacement string as parameters and returns a new string with one or more matches replaced.
To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.
The following finds the first instance of a p element and removes it from the DOM if it's html is equal to "
" like you specified.
if ($("p:first").html() == " ")
$("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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With