如果我有以下情况:
<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之类的函数吗?
发布于 2014-07-09 20:50:27
下面的代码有点让人耳目一新:我把它写成一行代码,但是我在这里把它分成了几行。但是,这将为您提供一个普通的对象,其中键是属性名,值是对应属性的值。
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并在其上调用一个数组函数,但这次我们使用的是map而不是reduce。您可以将map看作是reduce的特例:它总是为原始元素中的每个元素构建一个数组,其中包含一个元素。因此,您甚至不需要提到正在构建的对象:回调函数只有一个参数,我们只需要返回到新Array中的内容。一旦完成,我们就有了一个‘name=’值的数组,然后我们就将它与‘’连接起来。
发布于 2014-07-09 20:15:16
您可以尝试以下方法:
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);发布于 2014-07-09 20:23:44
它不是一个内置的属性,但是您可以使用类似数组的对象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""https://stackoverflow.com/questions/24662927
复制相似问题