简体   繁体   中英

How to convert HTML DOM structure

I have different requirement for my webpage. For that I need to change the DOM elements. I will have the html from server through AJAX. Html is come from server for different pages is different. Like,

<h1> Some text </h1>
Text out of tags
<div> 
 <p> Text in div </p>
 <img src="some-image.jpg" />
</div>
<p> <a href="#"> Some other text </a> </p>
<p> Some other text </p>
<img src="some-image.png" />

Something like that.

When it appears in webpage, It would be like,

Some text Text out of tags

Text in div An Image

Some other text

Some other text

Another Image

So, what I need is, I want to convert the above HTML DOM structure as follows by using Javascript or jQuery.

<p> Some text Text out of tags Text in div</p>
<img src="some-image.jpg" />
<p> Some other text </p>
<p> Some other text </p>
<img src="some-image.png" />

I just want text through <p> tags and images through <img> tags. I don't require remaining all other stuff.

If it is possible, please help me. Any help would be appreciated.

You can use

$("<selector>").contents().unwrap();

with all the element you want to remove. For example:

 $(document).ready(function() { $('h1, div, a').contents().unwrap(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <h1> Some text </h1> </p> <div> <img src="some-image.jpg" /> </div> <p> <a href="#"> Some other text </a> </p> <p> Some other text </p> <img src="some-image.png" /> 

Similar to this question remove parent element but keep the child element using jquery in HTML

use replaceWith() and return the element you want

You can manipulate/edit the DOM structure received from the server. To hide certain <div> or <p> elements, try following :

document.getElementById("divWithImage").style.display = "none";
                                                        ^^^^^^

Of course this will hide everything inside, so you should get hold of the inside contents like <img> and inject them again in the DOM at desired location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM