有没有相当于elem.innerHTML获取标签体中的代码?

时间:2014-07-09 20:08:26

标签: javascript html dom

如果我有以下内容:

<p class="demo" id="first_p">
    This is the first paragraph in the page and it says stuff in it.
</p>

我可以用

document.getElementById("first_p").innerHTML

获取

This is the first paragraph in the page and it says stuff in it. 

但是有什么简单的你可以运行,它将作为一个字符串返回

class="demo" id="first_p"

我知道我可以遍历所有元素的属性来单独获取每个元素但是有一个函数返回tagHTML或类似的东西吗?

5 个答案:

答案 0 :(得分:1)

您可以尝试以下方法: -

      var attributes = '';
            for(var i=0; i<document.getElementById("first_p").attributes.length; i++){
                var attr = document.getElementById("first_p").attributes[i];
                attributes += attr.nodeName+"='"+attr.nodeValue+"' "
            }
            console.log(attributes);

答案 1 :(得分:1)

它不是内置属性,但您可以使用类似数组的对象attributes来获取您正在寻找的内容。

Array.prototype.map.call(element.attributes, function (el) {
  return el.name + '="' + el.value + '"';
}).join(' ')

假设浏览器支持map功能。 Array.prototype.map.call部分是因为attributes实际上并不是一个数组,并且没有join方法,但因为它是一个类似数组的JavaScript的动态允许我们无论如何要打电话给map

带有页脚div的当前页面的示例:

var element = document.getElementById('footer')
Array.prototype.map.call(element.attributes, function (el) {
  return el.name + '="' + el.value + '"';
}).join(' ');
// "id="footer" class="categories""

答案 2 :(得分:1)

下面的代码是令人满意的:我把它写成一个单行,但我在这里把它分成了几行。但这将为您提供一个普通对象,其中键是属性名称,值是相应属性的值

Array.prototype.reduce.call(
    document.getElementById('first_p').attributes,
    function (attributes, currentAttribute) {
        attributes[currentAttribute.name] = currentAttribute.value;
        return attributes;
    },
    {}
);

通过这个,document.getElementById('first_p').attributes获取元素属性的NamedNodeMap。 NamedNodeMap不是数组,但Array.prototype.reduce.call(...)在NamedNodeMap上调用Array.prototype.reduce,就像它是一个数组一样。我们可以这样做,因为编写了NamedNodeMap,因此可以像数组一样访问它。

但我们不能止步于此。我提到的NamedNodeMap是一个Attr对象数组,而不是名称 - 值对的对象。我们需要转换它,这是Array.prototype.reduce的其他参数发挥作用的地方。

如果没有以奇怪的方式调用它,Array.prototype.reduce会有两个参数。第二个参数(由于我们称之为第三个参数,对我们来说是第三个)是我们想要构建的对象。在我们的例子中,这是一个全新的裸露对象:你最后看到的{}

Array.prototype.reduce的第一个参数(对我们来说又是第二个)是另一个函数。对于循环中的每个项,该函数将被调用一次,但它需要两个参数。 第二个参数是当前循环项,这很容易理解,但第一个参数有点疯狂。 第一个时间我们称之为该函数,它的第一个参数是我们想要建立的对象(即Array.prototype.reduce的最后一个参数。每次之后,第一个参数就是那个函数在最后一次调用时返回。Array.prototype.reduce返回对其内部函数的最后一次调用返回的内容。

所以我们从一个空对象开始。然后对于元素属性中的每个Attr,我们向对象添加一些东西,然后返回它。当最后一个调用结束时,对象结束,所以我们返回。这就是我们制作属性列表的方式。

如果你想要标签中的确切代码,比如字符串,那么我担心没有标准功能可以准确地获得它。 但是我们可以使用类似的设置来接近该代码

Array.prototype.map.call(
    document.getElementById('first_p').attributes,
    function (currentAttribute) {
        return currentAttribute.name + '=' + JSON.stringify(currentAttribute.value);
    }
).join(' ');

基本原理是一样的:我们接受NamedNodeMap并在其上调用一个Array函数,但这次我们使用的是map而不是reduce。您可以将map视为reduce的特例:它始终构建一个Array,其中一个元素用于原始元素中的每个元素。因此,你甚至不需要提到你正在构建的对象:回调函数只有一个参数,我们只返回要放入新数组的东西。完成后,我们会有一个'name =“value”'字符串数组,然后我们就加入''。

答案 3 :(得分:0)

您可以使用document.getElementById("first_p").attributes获取该DOM元素上所有属性的数组

如果你想在一个字符串中使用它们,只需执行:document.getElementById("first_p").attributes.join(' ')以获得所需的输出

答案 4 :(得分:0)

嗯,虽然目前没有任何东西可以直接执行此操作(尽管使用Node属性的方法是一种更可靠的方法,但一种选择是自己创建此方法:

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 demo

相关问题