선택한 요소의 외부 HTML 가져 오기
jQuery를 사용하여 선택한 개체의 HTML을 가져 오려고합니다. 나는 그 .html()
기능을 알고있다 . 문제는 선택한 개체를 포함하는 HTML이 필요하다는 것입니다 (이 경우 .html()
행 내부의 셀만 반환 하는 테이블 행).
나는 주변을 검색하고 객체를 복제하고 새로 만든 div 등에 추가하는 매우 '해킹'유형의 방법을 찾았지만 이것은 정말 더러워 보입니다. 더 좋은 방법이 있습니까? 아니면 새 버전의 jQuery (1.4.2)가 어떤 종류의 outerHtml
기능을 제공합니까?
2014 편집 : 질문과이 답변은 2010 년의 것입니다. 당시에는 더 나은 해결책이 널리 사용되지 않았습니다. 이제 다른 많은 답변이 더 좋습니다. 예를 들어 Eric Hu 또는 Re Capcha입니다.
이 사이트는 당신을위한 해결책을 가지고있는 것 같습니다 : jQuery : outerHTML | Yelotofu
jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};
현재 (2012 년 5 월 1 일) 모든 주요 브라우저가 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('');
편집 : 기본 지원 통계 에 대한element.outerHTML
- 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 출시
함수를 생성 할 필요가 없습니다. 다음과 같이하십시오.
$('a').each(function(){
var s = $(this).clone().wrap('<p>').parent().html();
console.log(s);
});
(그런데 브라우저의 콘솔에 기록 된 내용이 표시됩니다. 2009 년경 이후 대부분의 최신 브라우저에는이 기능이 있습니다.)
마법은 결국 이것입니다.
.clone().wrap('<p>').parent().html();
복제는 실제로 DOM을 방해하지 않는다는 것을 의미합니다. 그것없이 실행하면 p
모든 하이퍼 링크 앞 / 뒤에 태그가 삽입 된 것을 볼 수 있습니다 (이 예에서). 이것은 바람직하지 않습니다. 예, .clone()
.
작동 방식은 각 a
태그를 p
가져 와서 RAM에 복제하고, 태그로 래핑하고 , p
태그를 의미하는 부모를 가져온 다음 innerHTML
속성 을 가져 오는 것입니다.
편집 : 입력이 적고 동일하게 작동하기 때문에 조언을 받고 div
태그를 p
태그로 변경 했습니다.
어떨까요 : prop('outerHTML')
?
var outerHTML_text = $('#item-to-be-selected').prop('outerHTML');
그리고 설정하려면 :
$('#item-to-be-selected').prop('outerHTML', outerHTML_text);
그것은 나를 위해 일했습니다.
추신 : 이것은 jQuery 1.6에 추가되었습니다 .
jQuery 확장 :
(function($) {
$.fn.outerHTML = function() {
return $(this).clone().wrap('<div></div>').parent().html();
};
})(jQuery);
다음과 같이 사용하십시오. $("#myTableRow").outerHTML();
Arpan에 동의합니다 (Dec 13 '10 5:59).
그의 방식은 클론을 사용하지 않기 때문에 실제로 훨씬 더 나은 방식입니다. 복제 방법은 자식 요소가 있고 IE가 실제로 outerHTML
속성을 가지고 있다는 것을 다른 사람이 신경 쓰지 않는 경우 매우 시간이 많이 걸립니다 (예, IE에는 실제로 몇 가지 유용한 트릭이 있습니다).
그러나 나는 아마도 그의 스크립트를 약간 다르게 만들 것입니다.
$.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;
}
};
진정한 jQuery-esque 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;
}
작업 데모 : http://jsfiddle.net/AndyE/WLKAa/
이를 통해에 인수를 전달할 outerHTML
수 있습니다.
- 취소 가능한 함수 —
function (index, oldOuterHTML) { }
— 반환 값이 요소의 새 HTMLfalse
이됩니다 (반환 되지 않는 한 ). - 각 요소의 HTML 대신 설정되는 문자열.
자세한 내용은 .NET 용 jQuery 문서를 참조하세요 html()
.
get (jQuery 객체와 일치하는 DOM 요소 검색)을 사용할 수도 있습니다 .
예 :
$('div').get(0).outerHTML;//return "<div></div>"
확장 방법으로 :
jQuery.fn.outerHTML = function () {
return this.get().map(function (v) {
return v.outerHTML
}).join()
};
또는
jQuery.fn.outerHTML = function () {
return $.map(this.get(), function (v) {
return v.outerHTML
}).join()
};
객관식을 선택하고 일치하는 모든 요소의 외부 html을 반환합니다.
$('input').outerHTML()
반환:
'<input id="input1" type="text"><input id="input2" type="text">'
FULL jQuery 플러그인을으로 만들려면 .outerHTML
js 파일에 다음 스크립트를 추가하고 헤더에 jQuery 뒤에 포함합니다.
업데이트 새 버전은 더 나은 제어와 jQuery 선택기 친화적 인 서비스를 제공합니다! :)
;(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);
이렇게하면 한 요소의 outerHTML을 얻을 수있을뿐만 아니라 한 번에 여러 요소의 배열 반환을 얻을 수도 있습니다! 다음과 같이 두 jQuery 표준 스타일 모두에서 사용할 수 있습니다.
$.outerHTML($("#eleID")); // will return outerHTML of that element and is
// same as
$("#eleID").outerHTML();
// or
$.outerHTML("#eleID");
// or
$.outerHTML(document.getElementById("eleID"));
여러 요소의 경우
$("#firstEle, .someElesByClassname, tag").outerHTML();
스 니펫 예 :
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>
당신은 또한 이렇게 할 수 있습니다
document.getElementById(id).outerHTML
여기서 id는 찾고있는 요소의 ID입니다.
Firefox에서 작동하는 outerHTML을 얻기 위해 Jessica의 솔루션 (Josh에 의해 편집 됨)을 사용했습니다. 그러나 문제는 그녀의 솔루션이 요소를 DIV로 래핑했기 때문에 내 코드가 손상되었다는 것입니다. 코드를 한 줄 더 추가하면 문제가 해결되었습니다.
다음 코드는 DOM 트리를 변경하지 않은 채로있는 outerHTML을 제공합니다.
$jq.fn.outerHTML = function() {
if ($jq(this).attr('outerHTML'))
return $jq(this).attr('outerHTML');
else
{
var content = $jq(this).wrap('<div></div>').parent().html();
$jq(this).unwrap();
return content;
}
}
그리고 다음과 같이 사용하십시오 : $ ( "# myDiv"). outerHTML ();
누군가가 유용하다고 생각하기를 바랍니다!
// no cloning necessary
var x = $('#xxx').wrapAll('<div></div>').parent().html();
alert(x);
여기 바이올린 : http://jsfiddle.net/ezmilhouse/Mv76a/
시나리오가 새 행을 동적으로 추가하는 경우 다음을 사용할 수 있습니다.
var row = $(".myRow").last().clone();
$(".myRow").last().after(row);
.myrow
is the classname of the <tr>
. It makes a copy of the last row and inserts that as a new last row. This also works in IE7, while the [0].outerHTML
method does not allow assignments in ie7
node.cloneNode() hardly seems like a hack. You can clone the node and append it to any desired parent element, and also manipulate it by manipulating individual properties, rather than having to e.g. run regular expressions on it, or add it in to the DOM, then manipulate it afterwords.
That said, you could also iterate over the attributes of the element to construct an HTML string representation of it. It seems likely this is how any outerHTML function would be implemented were jQuery to add one.
I've used Volomike's solution updated by Jessica. Just added a check to see if the element exists, and made it return blank in case it doesn't.
jQuery.fn.outerHTML = function() {
return $(this).length > 0 ? $(this).clone().wrap('<div />').parent().html() : '';
};
Of course, use it like:
$('table#buttons').outerHTML();
You can find a good .outerHTML() option here https://github.com/darlesson/jquery-outerhtml.
Unlike .html() that returns only the element's HTML content, this version of .outerHTML() returns the selected element and its HTML content or replaces it as .replaceWith() method but with the difference that allows the replacing HTML to be inherit by the chaining.
Examples can also be seeing in the URL above.
Note that Josh's solution only works for a single element.
Arguably, "outer" HTML only really makes sense when you have a single element, but there are situations where it makes sense to take a list of HTML elements and turn them into markup.
Extending Josh's solution, this one will handle multiple elements:
(function($) {
$.fn.outerHTML = function() {
var $this = $(this);
if ($this.length>1)
return $.map($this, function(el){ return $(el).outerHTML(); }).join('');
return $this.clone().wrap('<div/>').parent().html();
}
})(jQuery);
Edit: another problem with Josh's solution fixed, see comment above.
Anothe similar solution with added remove()
of the temporary DOM object.
I have made this simple test with outerHTML being tokimon solution (without clone), and outerHTML2 being jessica solution (clone)
console.time("outerHTML");
for(i=0;i<1000;i++)
{
var html = $("<span style='padding:50px; margin:50px; display:block'><input type='text' title='test' /></span>").outerHTML();
}
console.timeEnd("outerHTML");
console.time("outerHTML2");
for(i=0;i<1000;i++)
{
var html = $("<span style='padding:50px; margin:50px; display:block'><input type='text' title='test' /></span>").outerHTML2();
}
console.timeEnd("outerHTML2");
and the result in my chromium (Version 20.0.1132.57 (0)) browser was
outerHTML: 81ms
outerHTML2: 439ms
but if we use tokimon solution without the native outerHTML function (which is now supported in probably almost every browser)
we get
outerHTML: 594ms
outerHTML2: 332ms
and there are gonna be more loops and elements in real world examples, so the perfect combination would be
$.fn.outerHTML = function()
{
$t = $(this);
if( "outerHTML" in $t[0] ) return $t[0].outerHTML;
else return $t.clone().wrap('<p>').parent().html();
}
so clone method is actually faster than wrap/unwrap method
(jquery 1.7.2)
Here is a very optimized outerHTML plugin for jquery: (http://jsperf.com/outerhtml-vs-jquery-clone-hack/5 => the 2 others fast code snippets are not compatible with some browsers like FF < 11)
(function($) {
var DIV = document.createElement("div"),
outerHTML;
if ('outerHTML' in DIV) {
outerHTML = function(node) {
return node.outerHTML;
};
} else {
outerHTML = function(node) {
var div = DIV.cloneNode();
div.appendChild(node.cloneNode(true));
return div.innerHTML;
};
}
$.fn.outerHTML = function() {
return this.length ? outerHTML(this[0]) : void(0);
};
})(jQuery);
@Andy E => I don't agree with you. outerHMTL doesn't need a getter AND a setter: jQuery already give us 'replaceWith'...
@mindplay => Why are you joining all outerHTML? jquery.html return only the HTML content of the FIRST element.
(Sorry, don't have enough reputation to write comments)
Short and sweet.
[].reduce($('.x'), function(i,v) {return i+v.outerHTML}, '')
or event more sweet with help of arrow functions
[].reduce.call($('.x'), (i,v) => i+v.outerHTML, '')
or without jQuery at all
[].reduce.call(document.querySelectorAll('.x'), (i,v) => i+v.outerHTML, '')
or if you don't like this approach, check that
$('.x').get().reduce((i,v) => i+v.outerHTML, '')
This is quite simple with vanilla JavaScript...
document.querySelector('#selector')
This is great for changing elements on the dom but does NOT work for ie when passing in a html string into jquery like this:
$('<div id="foo">Some <span id="blog">content</span></div>').find('#blog').outerHTML();
After some manipulation I have created a function which allows the above to work in ie for html strings:
$.fn.htmlStringOuterHTML = function() {
this.parent().find(this).wrap('<div/>');
return this.parent().html();
};
$.html = el => $("<div>"+el+"</div>").html().trim();
I came across this while looking for an answer to my issue which was that I was trying to remove a table row then add it back in at the bottom of the table (because I was dynamically creating data rows but wanted to show an 'Add New Record' type row at the bottom).
I had the same issue, in that it was returning the innerHtml so was missing the TR tags, which held the ID of that row and meant it was impossible to repeat the procedure.
The answer I found was that the jquery remove()
function actually returns the element, that it removes, as an object. So, to remove and re-add a row it was as simple as this...
var a = $("#trRowToRemove").remove();
$('#tblMyTable').append(a);
If you're not removing the object but want to copy it somewhere else, use the clone()
function instead.
jQuery plugin as a shorthand to directly get the whole element HTML:
jQuery.fn.outerHTML = function () {
return jQuery('<div />').append(this.eq(0).clone()).html();
};
And use it like this: $(".element").outerHTML();
$("#myNode").parent(x).html();
Where 'x' is the node number, beginning with 0 as the first one, should get the right node you want, if you're trying to get a specific one. If you have child nodes, you should really be putting an ID on the one you want, though, to just zero in on that one. Using that methodology and no 'x' worked fine for me.
Simple solution.
var myself = $('#div').children().parent();
$("#myTable").parent().html();
Perhaps I'm not understanding your question properly, but this will get the selected element's parent element's html.
Is that what you're after?
참고URL : https://stackoverflow.com/questions/2419749/get-selected-elements-outer-html
'code' 카테고리의 다른 글
jQuery를 사용하여 Bootstrap 모달 창을 여는 방법은 무엇입니까? (0) | 2020.09.30 |
---|---|
Git의 특정 개정판에서 단일 파일을 검색하는 방법 (0) | 2020.09.29 |
JavaScript를 사용하여 텍스트 입력 필드의 값을 어떻게 얻습니까? (0) | 2020.09.29 |
모바일 브라우저 감지 (0) | 2020.09.29 |
Markdown에서 이미지 크기 변경 (0) | 2020.09.29 |