简体   繁体   English

获取html div的确切内容

[英]Get the exact contents of an html div

Given this div on an html page : 给定这个div在html页面上:

<div id="div1"> <table> fred </div>

How can I use javascript to extract the contents of "div1" into a string, so that the string has this value : 如何使用javascript将“ div1”的内容提取到字符串中,以便该字符串具有以下值:

" <table> fred "

Using code such as : 使用如下代码:

var a = document.getElementById('div1').innerHTML;

is unsuccessful, because the browser adds markup to the string to try to create valid html table markup. 是不成功的,因为浏览器将标记添加到字符串中以尝试创建有效的html表标记。

As written in two other threads ( Get exact html() with closing tag for which starting tag is missing and Use javascript to get raw html code ), the only way to achieve what you want is by means of AJAX. 正如在其他两个线程中所写的那样( 获取缺少缺少起始标签的结束标签的确切html()使用javascript获取原始html代码 ),实现所需目标的唯一方法是AJAX。

bobince phrased it pretty well : bobince的表述很好

If you really really need to get your page's actual source HTML, you can make an XMLHttpRequest to your own URL ( location.href ) and get the full, unparsed HTML source in the responseText . 如果确实需要获取页面的实际源HTML,则可以对自己的URL( location.href )发出XMLHttpRequest ,并在responseText获取完整的未解析的HTML源。 There is almost never a good reason to do this. 几乎没有一个很好的理由要这样做。

Using innerHTML it's fine, but if you don't want the browser to fix your markup for you, you should use: 使用innerHTML很好,但是如果您不希望浏览器为您修复标记,则应使用:

<div id="div1"> &lt;table&gt; fred </div>

Otherwise you're writing invalid HTML 否则,您将编写无效的HTML

There is no way for it to ignore incorrect markup. 它无法忽略不正确的标记。 Either fix your markup or use &lt; 修正您的标记或使用&lt; and &gt; &gt; instead of < and > . 代替<>

Source: Why is my (incorrect) DOM structure auto-corrected after JQuery DOM manipulation? 来源: 为什么我的(不正确的)DOM结构在JQuery DOM操作后会自动更正?

只需使用Jquery:

$('#div1').html()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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