Javascript jQuery 获取 DOM 元素作为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8127091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:48:11  来源:igfitidea点击:

jQuery get DOM element as string

javascriptjquery

提问by bevacqua

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 上运行它?

UpdateI don't want to call .parent()since I have lots of other stuff in the parent element.

更新我不想打电话,.parent()因为我在父元素中有很多其他东西。

回答by WDuffy

How about

怎么样

$(selector).prop("outerHTML");

回答by Blazemonger

An old trick:

一个老套路:

var selector = ":input[type=text]:first";

var str = $(selector).clone().wrap('<div/>').parent().html();

UpdateYou don't need to worry about calling .parent()since you're working with an orphaned clone of the original selector.

更新您无需担心调用,.parent()因为您正在使用原始选择器的孤立克隆。

回答by John Hartsock

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/

回答by ThiagoPXP

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!

回答by Tarion

How about:

怎么样:

var str = $(selector)[0]

Maybe add a check that there is one element returned.

也许添加一项检查,以确保返回一个元素。