首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否有一个等价的elem.innerHTML来获取标记体中的代码?

是否有一个等价的elem.innerHTML来获取标记体中的代码?
EN

Stack Overflow用户
提问于 2014-07-09 20:08:25
回答 5查看 140关注 0票数 1

如果我有以下情况:

代码语言:javascript
运行
复制
<p class="demo" id="first_p">
    This is the first paragraph in the page and it says stuff in it.
</p>

我可以用

代码语言:javascript
运行
复制
document.getElementById("first_p").innerHTML

要获得

代码语言:javascript
运行
复制
This is the first paragraph in the page and it says stuff in it. 

但是,有什么简单的东西可以作为字符串返回吗?

代码语言:javascript
运行
复制
class="demo" id="first_p"

我知道我可以遍历元素的所有属性来获得每个属性,但是有返回tagHTML之类的函数吗?

EN

Stack Overflow用户

发布于 2014-07-09 20:27:35

虽然目前还没有任何方法可以直接做到这一点(尽管使用Node属性的方法是一种更可靠的方法,但有一种选择是自己创建该方法:

代码语言:javascript
运行
复制
HTMLElement.prototype.tagHTML = function(){
    // we create a clone to avoid doing anything to the original:
    var clone = this.cloneNode(),
    // creating a regex, using new RegExp, in order to create it
    // dynamically, and inserting the node's tagName:
        re = new RegExp('<' + this.tagName + '\\s+','i'),
    // 'empty' variables for later:
        closure, str;

    // removing all the child-nodes of the clone (we only want the
    // contents of the Node's opening HTML tag, so remove everything else):
    while (clone.firstChild){
        clone.removeChild(clone.firstChild);
    }

    // we get the outerHTML of the Node as a string,
    // remove the opening '<' and the tagName and a following space,
    // using the above regular expression:
    str = clone.outerHTML.replace(re,'');

    // naively determining whether the element is void
    // (ends with '/>') or not (ends with '>'):
    closure = str.indexOf('/>') > -1 ? '/>' : '>';

    // we get the string of HTML from the beginning until the closing
    // string we assumed just now, and then trim any leading/trailing
    // white-space using trim(). And, of course, we return that string:
    return str.substring(0,str.indexOf(closure)).trim();
};

console.log(document.getElementById('test').tagHTML());
console.log(document.getElementById('demo').tagHTML());

JS Fiddle演示

票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24662927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档