簡體   English   中英

如何轉換HTML DOM結構

[英]How to convert HTML DOM structure

我對網頁有不同的要求。 為此,我需要更改DOM元素。 我將通過AJAX從服務器獲取html。 HTML來自服務器的不同頁面是不同的。 喜歡,

<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" />

這樣的事情。

當它出現在網頁上時,就像

一些文字文字超出標簽

div中文本圖像

其他一些文字

其他一些文字

另一張圖片

所以,我需要的是,我想通過使用Javascript或jQuery將上述HTML DOM結構轉換如下。

<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" />

我只希望文本通過<p>標簽和圖像通過<img>標簽。 我不需要保留所有其他內容。

如果有可能,請幫助我。 任何幫助,將不勝感激。

您可以使用

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

與您要刪除的所有元素。 例如:

 $(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" /> 

與此問題類似, 刪除父元素,但在HTML中使用jquery保留子元素

使用replaceWith()並返回所需的元素

您可以操縱/編輯從服務器收到的DOM結構。 要隱藏某些<div><p>元素,請嘗試以下操作:

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

當然,這會將所有內容隱藏在里面,因此您應該掌握<img>類的內部內容,然后將它們再次插入DOM中所需的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM