如何转换HTML DOM结构 [英] How to convert HTML DOM structure

查看:235
本文介绍了如何转换HTML DOM结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的网页不同的要求。为此,我需要改变DOM元素。我将通过AJAX有来自服务器的HTML。 HTML是来自服务器不同的页面是不同的。就像,

 < H1>有些文字< / H1>
从文本标签
< D​​IV>
 &所述p为H.;文字DIV< / P>
 < IMG SRC =一些-image.jpg文件/>
< / DIV>
&所述p为H.; &所述; A HREF =#>其他一些文字< / A> &所述; / P>
&所述p为H.;其他一些文字< / P>
< IMG SRC =一些-image.png/>

类似的东西。

当它出现在网页上,这就好比,

某些文本文本出来的标签

在文字DIV的图片

其他的一些文本

其他的一些文本

另外图片

所以,我需要的是,我想上面的HTML DOM结构转换使用Javascript或jQuery的如下:

 < P>有些文字文本出DIV&LT标签文本; / P>
< IMG SRC =一些-image.jpg文件/>
&所述p为H.;其他一些文字< / P>
&所述p为H.;其他一些文字< / P>
< IMG SRC =一些-image.png/>

我只是想通过&LT文本; P> &LT标记和图像; IMG> 标记。我不要求所有剩余其他的东西。

如果有可能,请帮助我。
任何帮助将是AP preciated。


解决方案

您可以使用

$(<选择>中)的内容()解开();

所有要删除的元素。
例如:

\r
\r

$(文件)。就绪(函数(){\r
  $('H1,DIV,一个')的内容()解开()。\r
});

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/jquery/2.1.1/jquery.min.js\"></script>\r
&所述p为H.; &LT; H1&GT;有些文字&lt; / H1&GT; &所述; / P&GT;\r
&LT; D​​IV&GT; &LT; IMG SRC =一些-image.jpg文件/&GT; &LT; / DIV&GT;\r
&所述p为H.; &所述; A HREF =#&GT;其他一些文字&lt; / A&GT; &所述; / P&GT;\r
&所述p为H.;其他一些文字&lt; / P&GT;\r
&LT; IMG SRC =一些-image.png/&GT;

\r

\r
\r

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

这篇关于如何转换HTML DOM结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆