Remove divs from html source code

I have html code in which there are many divs and want to remove some divs from this code, it is so difficult to do with substr() or a similar php string function, maybe this is the best way to do this?

+4
source share
6 answers

You can do this with javascript. Just give unique div identifiers, then you can write simple javascript like this.

  document.getElementById('divid').remove(); 

Note. Before running remove (), load the item (s). . You can do this with jquery .

 $(document).ready(function(){ document.getElementById('divid').remove(); }); 

Alertnativly, if you decide to add elements, perhaps some time after loading the document , and then delete them, you can check if the element exists with the following code. (using the jquery library again) can also use the css selector with the object since you are using jquery.

 if ($("#divid").length > 0){ $('#divid').remove(); } 

This code can be convenient if you say that you are gradually adding elements to the document using the real-time comment system, you can use setInterval () to check if the element exists, and when it does, delete it.


If you NEED to do this with php, then Brian Agnew's answer to using an HTML PHP parser should solve your problem.

+2
source
+4
source

I suggest you check out the HTML HTML parser to do this reliably.

+3
source

Can you tell us more about your use case? I would do it in JS - give the divs you want to remove, for example the .remove class, and then follow these steps in jQuery:

 $(document).ready(function(){ $('.remove').remove() }); 

Alternatively, parsing HTML in php and removing it there would be a way to do this.

+2
source

Great opportunity to use DOMDocument for parsing HTML.

 $html = new DOMDocument(); $html->loadHTML($html_string); 

Then you can use any of the available methods to find and remove elements from the document, for example getElementsByTagName . Then you need to remove them from $html and re-export the document ( $html->saveHTML() )

+2
source
 >try this.. ;) > str_replace("<div>","") and > str_replace("</div>","") 
0
source

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


All Articles