简体   繁体   English

返回元素的html和jquery中的元素

[英]Returning html of an element along with the element in jquery

I have mark up like 我有喜欢

<div id="div1">
   <div id="div2">
     blah blah
   </div>
</div>

If I use $("#div1").html(), it returns the div#div2. 如果我使用$(“#div1”)。html(),它将返回div#div2。 But I want to get the complete html. 但我想获得完整的HTML。 ie, along with div#div1. 即,连同div#div1。

Is there any way to do this? 有什么办法吗?

You could try: 您可以尝试:

$('#div1')[0].outerHTML

EDIT: 编辑:

The same solution but without using jQuery (better performance): 相同的解决方案,但不使用jQuery(性能更高):

document.getElementById('div1').outerHTML

我会说尝试选择父元素,或者另一种方法是这样做:

var html = $('<div>').append($('#top').clone()).remove().html();

Use .parent(): 使用.parent():

$("#div1").parent().html();

However this will also get the html for all siblings. 但是,这也会为所有兄弟姐妹获取html。 You could just wrap div1 in another div... :) 您可以将div1换成另一个div ... :)

.html() returns innerHTML you need outerHTML. .html()返回您所需的externalHTML的innerHTML this can be helpful. 可能会有所帮助。

Try this : http://jsfiddle.net/96u9c/3/ 试试这个: http : //jsfiddle.net/96u9c/3/

:) special need function, now you can use it for any purpose of your own. :)特殊需要的功能,现在您可以将其用于自己的任何目的。

justtext will get you the only text for parent tag where as inner version will get you children text. justtext将为您提供父标记的唯一文本,而inner版本将为您提供子文本。

Hope it helps :) 希望对您有所帮助:)

You could very well add this to your common javascript file in project or customize it and use it as a plugin in your project. 您可以很好地将其添加到项目中的通用javascript文件中,或对其进行自定义并将其用作项目中的插件。

code

jQuery.fn.justtext = function() {

    return $(this).clone()
            .children()
            .remove()
            .end()
            .text();

};

jQuery.fn.justtextinner = function() {

    return $(this).clone()
            .children()
            .end()
            .text();

};

alert($('#div1').justtextinner());​
$("<div />").append($("#div1").clone()).html();

小提琴

You could create a simple jQuery plugin that would do the job for you, allowing you to use the native .outerHTML property when it exists, or polyfill it when it doesn't. 您可以创建一个简单的jQuery插件来为您完成这项工作,允许您在原生.outerHTML属性存在时使用它,或在不存在时使用.outerHTML属性。

(function($) {
  if('outerHTML' in document.createElement('div')) {
    $.fn.outerHtml = function() {
      return this[0].outerHTML;
    }
  }
  else {
    $.fn.outerHtml = function() {
      return $("<div />").append(this.eq(0).clone()).html();
    }
  }
}(jQuery));

An example is at http://jsfiddle.net/steveukx/qUEyp/ 一个示例在http://jsfiddle.net/steveukx/qUEyp/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM