如果我有以下情况:
<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:27:35
虽然目前还没有任何方法可以直接做到这一点(尽管使用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演示。
https://stackoverflow.com/questions/24662927
复制相似问题