JQuery Replace 1st instance of text

If I have a text like this:

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

I need the jQuery part that will replace the first instance with only <p>&nbsp;</p> by '..

Thus, 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 not do anything.

EDIT

I tried to implement a solution from @Joey C., but I can't get it to work. There is simply no to remove.

 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()); 
+4
source share
2 answers

The following finds the first instance of the p element and removes it from the DOM if its html is " &nbsp; " as you indicated.

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

If html is stored as a string in the myHTML variable, you can create a DOM element and do a similar comparison. When testing, I found that it works better if you wrap the elements you create with the 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()); 

In fact, this will not update the line containing the html source code, so you should reassign it if it is still needed in this variable.

  myHTML = newElement.html(); 
+8
source

I like 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 a list of items to process, I would give them a class, say 'foo', and process them using jQuery

 $('.foo').each(ProcessParagraphs); 
+1
source

Source: https://habr.com/ru/post/1314036/


All Articles