![](/img/trans.png)
[英]Pure JavaScript - edit text in DOM element without touching child elements
[英]Getting a HTML element DOM as string using javascript without child elements
我想知道是否有任何方法來獲取html元素/節點而不將其子級作為字符串。
這個問題似乎像是這個問題的重復: jQuery,獲取整個元素的html 。
但是我只希望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" />'});
小提琴:
http://jsfiddle.net/ttoom9hc/12/
從其他帖子中查找:
http://jsfiddle.net/u6avkvz0/
我能想到的最簡單的方法是克隆它與淺DOM的cloneNode
,然后拿到outerHTML
的是:
var element = $("selector for the element you want");
var html = element[0].cloneNode(false).outerHTML;
例子 (我自己做了, 哇那小提琴很復雜)
或使用更多jQuery: 示例
var html = $("selector for the element you want")
.clone()
.contents()
.remove()
.end()[0].outerHTML;
請注意,元素內的文本是“子級”內容(特別是一個或多個“ Text
節點的子級)。 如果需要這些,則需要循環。 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.