如何获取innerHtml,包括标签,使用jQuery? [英] How to get the innerHtml, including the tag, using jQuery?

查看:642
本文介绍了如何获取innerHtml,包括标签,使用jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



其实问题是,让我说我是这段代码。

 < span id =spanIDxxstyle =blah-blah> 
< tag1>此处的代码< / tag2>示例文本
< tag2>代码这里< / tag2> html aass hhddll
示例文本
< / span>

现在,我将使用代码。

  jQuery的( #spanIDxx)HTML(); 

然后它将只返回innerHTML,不包括< span id =spanIDxx style =blah-blah>

但我想要的东西可以返回innerHTML包括指定的元素。

解决方案

这将创建一个新的 div 并将元素的克隆附加到 div 。新的 div 永远不会插入到DOM中,所以它不会影响你的页面。

  var theResult = $('< div />')。append($(#spanIDxx)。clone())。html() 

alert(theResult);

如果您需要频繁使用,不想再添加另一个插件,只需使其成为一个函数:

  function htmlInclusive(elem){return $('< div />')追加($(ELEM).clone())HTML()。 } 

alert(htmlInclusive(#spanIDxx));

或自己扩展jQuery:

 $ fn.htmlInclusive = function(){return $('< div />')append($(this).clone())。 } 

alert($(#spanIDxx)。htmlInclusive());


Sorry, if the title is too obscure ;D.

Actually the problem is, lets say i am this code.

<span id="spanIDxx" style="blah-blah">
   <tag1>code here </tag2> sample text 
   <tag2>code here </tag2> html aass hhddll
   sample text
</span>

Now if i will use the code.

jQuery("#spanIDxx").html();

then it will return just the innerHTML excluding <span id="spanIDxx" style="blah-blah">
but i want something which can return the innerHTML including the specified element.

解决方案

This will create a new div and append a clone of your element to that div. The new div never gets inserted into the DOM, so it doesn't affect your page.

var theResult = $('<div />').append($("#spanIDxx").clone()).html();

alert( theResult );

If you need to use this frequently, and don't want to bother with adding yet another plugin, just make it into a function:

function htmlInclusive(elem) { return $('<div />').append($(elem).clone()).html(); }

alert( htmlInclusive("#spanIDxx") );

Or extend jQuery yourself:

$.fn.htmlInclusive = function() { return $('<div />').append($(this).clone()).html(); }

alert( $("#spanIDxx").htmlInclusive() );

这篇关于如何获取innerHtml,包括标签,使用jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆