如何将HTML元素转换为字符串,包括打开和结束标记?

时间:2022-08-27 17:08:20

Suppose I have the following HTML element:

假设我有以下HTML元素:

<span id='kuku' class='lala bubu' value='xyz'>some text</span>

I know that .html() returns the inner part of the element, i.e. some text.

我知道。html()返回元素的内部部分,即一些文本。

How could I get the whole element as string, containing <span>...</span>?

如何将整个元素作为字符串,包含?

4 个解决方案

#1


13  

Most browsers support the element.outerHTML property. You may also want to check out the following Stack Overflow post for an alternative solution (for non IE browsers):

大多数浏览器都支持该元素。outerHTML财产。您可能还想要查看以下堆栈溢出贴子,以获得替代解决方案(对于非IE浏览器):

#2


7  

Try this:

试试这个:

alert($('#kuku').clone().wrapAll("<div/>").parent().html());
  • clones the element you want
  • 克隆您想要的元素
  • wraps it in a div
  • 用div包装它
  • selects the parent (the new div)
  • 选择父类(新div)
  • gets the HTML
  • 得到的HTML

#3


3  

You can also do it like this:

你也可以这样做:

alert( $('<div>').append( $("#kuku").clone() ).html() );

This one creates an empty div and appends a copy / clone of the element with id kuku to it. It then returns the innerHTML of that previously empty div, which now has in it precisely the HTML you are after.

它创建一个空div,并向其添加id为kuku的元素的副本/克隆。然后,它返回先前空div的innerHTML,它现在正好包含您要的HTML。

#4


1  

Simply get the owner of the span. So use the id of the owner/container of the span and use

只需获取span的所有者。因此,使用span的所有者/容器的id并使用

document.getElementById("urSpanOwnerID").innerHTML

.innerHTML . getelementbyid(“urSpanOwnerID”)

#1


13  

Most browsers support the element.outerHTML property. You may also want to check out the following Stack Overflow post for an alternative solution (for non IE browsers):

大多数浏览器都支持该元素。outerHTML财产。您可能还想要查看以下堆栈溢出贴子,以获得替代解决方案(对于非IE浏览器):

#2


7  

Try this:

试试这个:

alert($('#kuku').clone().wrapAll("<div/>").parent().html());
  • clones the element you want
  • 克隆您想要的元素
  • wraps it in a div
  • 用div包装它
  • selects the parent (the new div)
  • 选择父类(新div)
  • gets the HTML
  • 得到的HTML

#3


3  

You can also do it like this:

你也可以这样做:

alert( $('<div>').append( $("#kuku").clone() ).html() );

This one creates an empty div and appends a copy / clone of the element with id kuku to it. It then returns the innerHTML of that previously empty div, which now has in it precisely the HTML you are after.

它创建一个空div,并向其添加id为kuku的元素的副本/克隆。然后,它返回先前空div的innerHTML,它现在正好包含您要的HTML。

#4


1  

Simply get the owner of the span. So use the id of the owner/container of the span and use

只需获取span的所有者。因此,使用span的所有者/容器的id并使用

document.getElementById("urSpanOwnerID").innerHTML

.innerHTML . getelementbyid(“urSpanOwnerID”)