[英]jQuery get DOM element as string
Say I have 说我有
$(":input[type=text]:first")
How do I get 如何得到
<input type="text" value="" size="28" maxlength="140" tabindex="1" placeholder="search" class="textbox" name="q" autocomplete="off">
Assuming I run this on SO? 假设我在SO上运行它?
Update I don't want to call .parent()
since I have lots of other stuff in the parent element. 更新我不想调用
.parent()
因为我在父元素中有很多其他东西。
怎么样
$(selector).prop("outerHTML");
var selector = ":input[type=text]:first";
var str = $(selector).clone().wrap('<div/>').parent().html();
Update You don't need to worry about calling .parent()
since you're working with an orphaned clone of the original selector. 更新您不必担心调用
.parent()
因为您正在使用原始选择器的孤立克隆。
Use jQuery.html() by appending to a created element. 通过附加到创建的元素来使用jQuery.html() 。
$('<div/>').append($(":input[type=text]:first").clone()).html()
Here is a fiddle providing an example: http://jsfiddle.net/Zwbmx/1/ 这是一个提供示例的小提琴: http : //jsfiddle.net/Zwbmx/1/
Following on what @Blazemonger have answered, if you are going to send this html content to the server, it's worth to get rid of all unnecessary tags, white-spaces and line-breaks that don't add any value. 关于@Blazemonger已经回答的内容,如果你要将这个html内容发送到服务器,那么删除所有不添加任何值的不必要的标签,空格和换行符是值得的。
var quote = $(".invoice") //get hidden print-version DOM element
.clone()
.wrap('<div/>')
.parent()
.html()
.replace(/ /g, '') //get rid of indentation spaces
.replace(/(\r\n|\n|\r)/gm, "") //get rid of line breaks
.replace(/<!--[\s\S]*?-->/g, ""); //get rid of comment tags
My html had 50kb, after getting rid of this stuff, it got reduced to 4kb! 我的html有50kb,在摆脱这些东西后,它减少到4kb!
How about: 怎么样:
var str = $(selector)[0]
Maybe add a check that there is one element returned. 也许添加一个检查,返回一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.