如何将jQuery对象转换为字符串?


当前回答

只需使用.get(0)来获取本机元素,并获取其outerHTML属性:

var $elem = $('<a href="#">Some element</a>');
console.log("HTML is: " + $elem.get(0).outerHTML);

其他回答

你能说得更具体一点吗?如果你想让HTML在一个标签里面,你可以这样做:

HTML代码片段:

<p><b>This is some text</b></p>

jQuery:

var txt = $('p').html(); // Value of text is <b>This is some text</b>

找出HTML节点(对象)可用的属性和方法的最好方法是这样做:

console.log($("#my-node"));

从jQuery 1.6+你可以使用outerHTML包括HTML标签在你的字符串输出:

var node = $("#my-node").outerHTML;

jQuery在这里,所以:

jQuery.fn.goodOLauterHTML= function() {
    return $('<a></a>').append( this.clone() ).html();
}

返回所有HTML内容:

$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all

这对我来说似乎很有效:

$("#id")[0].outerHTML

接受的答案不包括文本节点(未定义被打印出来)。

下面的代码片段解决了这个问题:

var htmlElements = $('<p><a href="http://google.com">google</a></p>↵↵<p><a href="http://bing.com">bing</a></p>'), htmlString = ''; htmlElements.each(function () { var element = $(this).get(0); if (element.nodeType === Node.ELEMENT_NODE) { htmlString += element.outerHTML; } else if (element.nodeType === Node.TEXT_NODE) { htmlString += element.nodeValue; } }); alert('String html: ' + htmlString); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>