获取包含属性的开始标记 - 没有innerHTML的outerHTML [英] get opening tag including attributes - outerHTML without innerHTML

查看:89
本文介绍了获取包含属性的开始标记 - 没有innerHTML的outerHTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从DOM中检索某个带有其属性的标记元素。例如,来自

I would like to retrieve a certain tag element with its attributes from the DOM. For example, from

<a href="#" class="class">
  link text
</a>

我想得到< a href =#class =类> ,可选择关闭< / a> ,作为字符串或其他对象。
在我看来,这类似于检索 .outerHTML 而没有 .innerHTML

I want to get <a href="#" class="class">, optionally with a closing </a>, either as a string or some other object. In my opinion, this would be similar to retrieving the .outerHTML without the .innerHTML.

最后,我需要通过jQuery包装其他一些元素。我试过

Finally, I need this to wrap some other elements via jQuery. I tried

var elem = $('#some-element').get(0);
$('#some-other-element').wrap(elem);

.get()返回DOM元素包括其内容。另外

but .get() returns the DOM element including its content. Also

var elem = $('#some-element').get(0);
$('#some-other-element').wrap(elem.tagName).parent().attr(elem.attributes);

失败,因为 elem.attributes 返回 NamedNodeMap 哪个不适用于jQuery的 attr()而且我无法转换它。
承认以上示例不是很有意义,因为它们还复制了元素的不再唯一ID。但有什么简单的方法吗?非常感谢。

fails as elem.attributes returns a NamedNodeMap which does not work with jQuery's attr() and I was not able to convert it. Admitted that the above examples are not very senseful as they copy also the element's no-longer-unique ID. But is there any easy way? Thanks alot.

推荐答案

var wrapper = $('.class').clone().attr('id','').empty();




  • 您可能希望将选择器更改为更精确地匹配< a> 您正在寻找的元素。

  • clone() 创建匹配元素的新副本,也可以选择复制事件处理程序。

  • 我使用 attr 来清除元素的ID,这样我们就不会重复ID。

  • < a href =http://www.jqapi.com/#p=empty =nofollow> empty() 删除所有子节点( ' innerHTML ')。

    • You might want to change the selector to more exactly match the <a> element you're looking for.
    • clone() creates a new copy of the matched element(s), optionally copying event handlers too.
    • I used attr to clear the element's ID so that we don't duplicate IDs.
    • empty() removes all child nodes (the 'innerHTML').
    • 这篇关于获取包含属性的开始标记 - 没有innerHTML的outerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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