jQuery 获取所选元素的外部 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2419749/
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
Get selected element's outer HTML
提问by Ryan
I'm trying to get the HTML of a selected object with jQuery. I am aware of the .html()
function; the issue is that I need the HTML including the selected object (a table row in this case, where .html()
only returns the cells inside the row).
我正在尝试使用 jQuery 获取所选对象的 HTML。我知道这个.html()
功能;问题是我需要包含所选对象的 HTML(在本例中为表格行,其中.html()
仅返回行内的单元格)。
I've searched around and found a few very ‘hackish' type methods of cloning an object, adding it to a newly created div, etc, etc, but this seems really dirty. Is there any better way, or does the new version of jQuery (1.4.2) offer any kind of outerHtml
functionality?
我四处搜索,发现了一些非常“hackish”类型的克隆对象、将其添加到新创建的 div 等的方法,但这似乎很脏。有没有更好的方法,或者新版本的 jQuery (1.4.2) 是否提供任何类型的outerHtml
功能?
采纳答案by David V.
2014 Edit : The question and this reply are from 2010. At the time, no better solution was widely available. Now, many of the other replies are better : Eric Hu's, or Re Capcha's for example.
2014 年编辑:问题和此回复来自 2010 年。当时,没有更好的解决方案可以广泛使用。现在,许多其他回复都更好:例如 Eric Hu 或 Re Capcha 的回复。
This site seems to have a solution for you : jQuery: outerHTML | Yelotofu
该站点似乎为您提供了一个解决方案: jQuery:outerHTML | 油豆腐
jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};
回答by Eric Hu
I believe that currently (5/1/2012), all major browsers support the outerHTML function. It seems to me that this snippet is sufficient. I personally would choose to memorize this:
我相信目前(5/1/2012),所有主流浏览器都支持outerHTML功能。在我看来,这个片段就足够了。我个人会选择记住这一点:
// Gives you the DOM element without the outside wrapper you want
$('.classSelector').html()
// Gives you the outside wrapper as well only for the first element
$('.classSelector')[0].outerHTML
// Gives you the outer HTML for all the selected elements
var html = '';
$('.classSelector').each(function () {
html += this.outerHTML;
});
//Or if you need a one liner for the previous code
$('.classSelector').get().map(function(v){return v.outerHTML}).join('');
EDIT: Basic support statsfor element.outerHTML
编辑:基本支持统计的element.outerHTML
- Firefox (Gecko): 11 ....Released 2012-03-13
- Chrome: 0.2 ...............Released 2008-09-02
- Internet Explorer 4.0...Released 1997
- Opera 7 ......................Released 2003-01-28
- Safari 1.3 ...................Released 2006-01-12
- Firefox (Gecko): 11 .... 2012-03-13 发布
- Chrome: 0.2 ...............于 2008-09-02 发布
- Internet Explorer 4.0... 1997 年发布
- Opera 7 ...................... 2003-01-28 发布
- Safari 1.3 ...................... 2006-01-12 发布
回答by Volomike
No need to generate a function for it. Just do it like this:
无需为其生成函数。只需这样做:
$('a').each(function(){
var s = $(this).clone().wrap('<p>').parent().html();
console.log(s);
});
(Your browser's console will show what is logged, by the way. Most of the latest browsers since around 2009 have this feature.)
(顺便说一下,您浏览器的控制台将显示记录的内容。自 2009 年左右以来的大多数最新浏览器都具有此功能。)
The magic is this on the end:
最后的魔法是这样的:
.clone().wrap('<p>').parent().html();
The clone means you're not actually disturbing the DOM. Run it without it and you'll see p
tags inserted before/after all hyperlinks (in this example), which is undesirable. So, yes, use .clone()
.
克隆意味着您实际上并没有干扰 DOM。在没有它的情况下运行它,您将看到p
在所有超链接之前/之后插入的标签(在本例中),这是不可取的。所以,是的,使用.clone()
.
The way it works is that it takes each a
tag, makes a clone of it in RAM, wraps with p
tags, gets the parent of it (meaning the p
tag), and then gets the innerHTML
property of it.
它的工作方式是获取每个a
标签,在 RAM 中复制它,用p
标签包装,获取它的父级(即p
标签),然后获取innerHTML
它的属性。
EDIT: Took advice and changed div
tags to p
tags because it's less typing and works the same.
编辑:接受建议并将div
标签更改为p
标签,因为它打字较少并且工作方式相同。
回答by Re Captcha
What about: prop('outerHTML')
?
呢:prop('outerHTML')
?
var outerHTML_text = $('#item-to-be-selected').prop('outerHTML');
And to set:
并设置:
$('#item-to-be-selected').prop('outerHTML', outerHTML_text);
It worked for me.
它对我有用。
PS: This is added in jQuery 1.6.
PS:这是在jQuery 1.6 中添加的。
回答by jessica
Extend jQuery:
扩展jQuery:
(function($) {
$.fn.outerHTML = function() {
return $(this).clone().wrap('<div></div>').parent().html();
};
})(jQuery);
And use it like this: $("#myTableRow").outerHTML();
并像这样使用它: $("#myTableRow").outerHTML();
回答by Tokimon
I agree with Arpan (Dec 13 '10 5:59).
我同意 Arpan(2010 年 12 月 13 日 5:59)。
His way of doing it is actually a MUCH better way of doing it, as you dont use clone. The clone method is very time consuming, if you have child elements, and nobody else seemed to care that IE actually HAVE the outerHTML
attribute (yes IE actually have SOME useful tricks up its sleeve).
他的做法实际上是一种更好的做法,因为您不使用克隆。克隆方法非常耗时,如果您有子元素,并且似乎没有其他人关心 IEouterHTML
是否实际拥有该属性(是的,IE 实际上有一些有用的技巧)。
But I would probably create his script a bit different:
但我可能会创建他的脚本有点不同:
$.fn.outerHTML = function() {
var $t = $(this);
if ($t[0].outerHTML !== undefined) {
return $t[0].outerHTML;
} else {
var content = $t.wrap('<div/>').parent().html();
$t.unwrap();
return content;
}
};
回答by Andy E
To be truly jQuery-esque, you might want outerHTML()
to be a getter anda setter and have its behaviour as similar to html()
as possible:
要成为真正的 jQuery 风格,您可能希望outerHTML()
成为一个 getter和一个 setter,并使其行为尽可能类似于html()
:
$.fn.outerHTML = function (arg) {
var ret;
// If no items in the collection, return
if (!this.length)
return typeof arg == "undefined" ? this : null;
// Getter overload (no argument passed)
if (!arg) {
return this[0].outerHTML ||
(ret = this.wrap('<div>').parent().html(), this.unwrap(), ret);
}
// Setter overload
$.each(this, function (i, el) {
var fnRet,
pass = el,
inOrOut = el.outerHTML ? "outerHTML" : "innerHTML";
if (!el.outerHTML)
el = $(el).wrap('<div>').parent()[0];
if (jQuery.isFunction(arg)) {
if ((fnRet = arg.call(pass, i, el[inOrOut])) !== false)
el[inOrOut] = fnRet;
}
else
el[inOrOut] = arg;
if (!el.outerHTML)
$(el).children().unwrap();
});
return this;
}
Working demo: http://jsfiddle.net/AndyE/WLKAa/
This allows us to pass an argument to outerHTML
, which can be
这允许我们向 传递一个参数outerHTML
,它可以是
- a cancellable function —
function (index, oldOuterHTML) { }
— where the return value will become the new HTML for the element (unlessfalse
is returned). - a string, which will be set in place of the HTML of each element.
- 一个可取消的函数——
function (index, oldOuterHTML) { }
其中返回值将成为元素的新 HTML(除非false
返回)。 - 一个字符串,它将被设置来代替每个元素的 HTML。
For more information, see the jQuery docs for html()
.
有关更多信息,请参阅 jQuery 文档html()
。
回答by MJ Vakili
You can also use get(Retrieve the DOM elements matched by the jQuery object.).
您还可以使用get(检索与 jQuery 对象匹配的 DOM 元素。)。
e.g:
例如:
$('div').get(0).outerHTML;//return "<div></div>"
As extension method :
作为扩展方法:
jQuery.fn.outerHTML = function () {
return this.get().map(function (v) {
return v.outerHTML
}).join()
};
Or
或者
jQuery.fn.outerHTML = function () {
return $.map(this.get(), function (v) {
return v.outerHTML
}).join()
};
Multiple choice and return the outer html of all matched elements.
多选并返回所有匹配元素的外部 html。
$('input').outerHTML()
return:
返回:
'<input id="input1" type="text"><input id="input2" type="text">'
回答by SpYk3HH
To make a FULL jQuery plugin as .outerHTML
, add the following script to any js file and include after jQuery in your header:
要将完整的 jQuery 插件制作为.outerHTML
,请将以下脚本添加到任何 js 文件中,并在标题中包含在 jQuery 之后:
updateNew version has better control as well as a more jQuery Selector friendly service! :)
更新新版本具有更好的控制以及更 jQuery Selector 友好的服务!:)
;(function($) {
$.extend({
outerHTML: function() {
var $ele = arguments[0],
args = Array.prototype.slice.call(arguments, 1)
if ($ele && !($ele instanceof jQuery) && (typeof $ele == 'string' || $ele instanceof HTMLCollection || $ele instanceof Array)) $ele = $($ele);
if ($ele.length) {
if ($ele.length == 1) return $ele[0].outerHTML;
else return $.map($("div"), function(ele,i) { return ele.outerHTML; });
}
throw new Error("Invalid Selector");
}
})
$.fn.extend({
outerHTML: function() {
var args = [this];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.outerHTML.apply($, args);
}
});
})(jQuery);
This will allow you to not only get the outerHTML of one element, but even get an Array return of multiple elements at once! and can be used in both jQuery standard styles as such:
这将使您不仅可以获取一个元素的外层HTML,还可以一次获取多个元素的 Array 返回值!并且可以在两种 jQuery 标准样式中使用,例如:
$.outerHTML($("#eleID")); // will return outerHTML of that element and is
// same as
$("#eleID").outerHTML();
// or
$.outerHTML("#eleID");
// or
$.outerHTML(document.getElementById("eleID"));
For multiple elements
对于多个元素
$("#firstEle, .someElesByClassname, tag").outerHTML();
Snippet Examples:
片段示例:
console.log('$.outerHTML($("#eleID"))'+"\t", $.outerHTML($("#eleID")));
console.log('$("#eleID").outerHTML()'+"\t\t", $("#eleID").outerHTML());
console.log('$("#firstEle, .someElesByClassname, tag").outerHTML()'+"\t", $("#firstEle, .someElesByClassname, tag").outerHTML());
var checkThisOut = $("div").outerHTML();
console.log('var checkThisOut = $("div").outerHTML();'+"\t\t", checkThisOut);
$.each(checkThisOut, function(i, str){ $("div").eq(i).text("My outerHTML Was: " + str); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://rawgit.com/JDMcKinstry/ce699e82c7e07d02bae82e642fb4275f/raw/deabd0663adf0d12f389ddc03786468af4033ad2/jQuery.outerHTML.js"></script>
<div id="eleID">This will</div>
<div id="firstEle">be Replaced</div>
<div class="someElesByClassname">At RunTime</div>
<h3><tag>Open Console to see results</tag></h3>
回答by Andy
you can also just do it this way
你也可以这样做
document.getElementById(id).outerHTML
where id is the id of the element that you are looking for
其中 id 是您要查找的元素的 id