[英]Getting a HTML element DOM as string using javascript without child elements
I was wondering if there was any method to get a html element / node without its children as a string. 我想知道是否有任何方法来获取html元素/节点而不将其子级作为字符串。
This question might seem like a duplicate of this question: jQuery, get html of a whole element . 这个问题似乎像是这个问题的重复: jQuery,获取整个元素的html 。
But i only want the html element itself as a string, without its children. 但是我只希望html元素本身为字符串,而没有其子元素。
texts.push({title:'[#target, outerHTML]', value: $input[0].outerHTML});
texts.push({title:'[#target, $.html()]', value: $input.html()});
texts.push({title:'[#bigger_Target, outerHTML]', value: $('#bigger_Target')[0].outerHTML});
texts.push({title:'[#bigger_Target, $.html()]', value: $('#bigger_Target').html()});
texts.push({title:'[#target, DESIRED]', value: '<input class="test" data-type="text only" type="button" value="Test />"'});
texts.push({title:'[#bigger_Target, DESIRED]', value: '<div id="bigger_Target" />'});
FIDDLE: 小提琴:
http://jsfiddle.net/ttoom9hc/12/ http://jsfiddle.net/ttoom9hc/12/
FIDDLE FROM OTHER POST: 从其他帖子中查找:
http://jsfiddle.net/u6avkvz0/ http://jsfiddle.net/u6avkvz0/
The easiest way I can think of is to clone it shallow with DOM's cloneNode
, then get the outerHTML
of that: 我能想到的最简单的方法是克隆它与浅DOM的cloneNode
,然后拿到outerHTML
的是:
var element = $("selector for the element you want");
var html = element[0].cloneNode(false).outerHTML;
Example (made my own, wow was that fiddle complex) 例子 (我自己做了, 哇那小提琴很复杂)
Or with more jQuery: Example 或使用更多jQuery: 示例
var html = $("selector for the element you want")
.clone()
.contents()
.remove()
.end()[0].outerHTML;
Note that the text inside the element is "child" content (specifically, one or more Text
node children). 请注意,元素内的文本是“子级”内容(特别是一个或多个“ Text
节点的子级)。 If you want those, you'll need a loop. 如果需要这些,则需要循环。 jQuery's contents
can help there: Example jQuery的contents
可以帮助您: 示例
var html = $("selector for the element you want")
.clone()
.contents()
.each(function() {
if (this.nodeType !== 3) { // It's not a Text node...
$(this).remove(); // ...nuke it
}
})
.end()[0].outerHTML;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.