没有子元素的Javascript元素html [英] Javascript element html without children

查看:67
本文介绍了没有子元素的Javascript元素html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的javascript代码中,我需要获取元素的定义,但没有元素的内容-文本或子元素都没有.

In my javascript code I need to get the definition of an element, but without its content - neither text nor children.

例如用于:

<div id="my_example_id" class="ShinyClass">
   My important text
   <span> Here</span>
</div>

我想编写一个javascript功能,当上面的div元素提供该功能时,将以字符串形式返回以下内容:

I would like to write a javascript fucntion that when provided with the element of the div above will return the following as string:

<div id="my_example_id" class="ShinyClass">

我一直在尝试对元素进行不同的操作,例如 innerHTML outerHTML 之类的功能,但是我无法弄清楚如何仅提取我所需要的部分感兴趣.在第一个> 之前的子字符串是最好的解决方案吗?

I have been trying with different manipulations over the elements, functions like innerHTML, outerHTML and similar, but I was unable to figure out how to fetch only the part I am interested in. Is substring until the first > the best possible solution?

编辑:选择元素不是问题的一部分-我知道该怎么做,没有问题.问题在于:当我已经选择了一个特定元素时,如何仅将其自身的定义解析为字符串.

EDIT: selecting the element is not part of the question - I know how to do that, no prob. Rather the question is: when I have already selected a particular element how to parse as string only its own definition.

推荐答案

我猜想正则表达式就是您所需要的.检查是否适合您

I guess that a Regex is what you need. Check if this works for you

function getHtml(selector) {
  var element = document.querySelector(selector)
  var htmlText = element.outerHTML
  var start  = htmlText.search(/</)
  var end  = htmlText.search(/>/)
  return htmlText.substr(start, end + 1)
}
alert(getHtml('.ShinyClass'))

示例此处

这篇关于没有子元素的Javascript元素html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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