如果我的问题不明确,我不希望outerhtml返回节点内的所有内容。我不想要那些。例如:
<div id="foo" class="something" style="width:80%; display:inline-block">
Hello!
<div id="bar" class="something_else">
How are you?Hope you are doing well!
</div>
</div>
现在,'foo'的outerHTML将给出其DOM结构的整个字符串表示。我只想要
div id="foo" class="something" style="width:80%; display:inline-block"
是否可以在不使用正则表达式/字符串匹配的情况下获得此功能?
答案 0 :(得分:4)
您可以获取outerHTML,然后解析所需的部分:
console.log(
document.getElementById('foo').outerHTML.match(/<([^>]+)>/)[1]
);
<div id="foo" class="something" style="width:80%; display:inline-block">
Hello!
<div id="bar" class="something_else">
How are you?Hope you are doing well!
</div>
</div>
答案 1 :(得分:4)
使用javascript element.nodeName和element.attributes形成字符串:
var foo = document.getElementById('foo');
console.log(crazyString(foo));
function crazyString(el) {
var a = [el.nodeName];
var atts = el.attributes;
for (var i=0; i < atts.length; i++) {
a.push(atts[i].name + '="' + atts[i].value + '"');
}
return a.join(" ");
}
&#13;
<div id="foo" class="something" style="width:80%; display:inline-block">
Hello!
<div id="bar" class="something_else">
How are you?Hope you are doing well!
</div>
</div>
&#13;
答案 2 :(得分:1)
您可以尝试这样的事情,
var element = document.getElementById("foo");
var tag = element.tagName;
$.each(element.attributes, function() {
tag += " "+ this.name + '"'+ this.value+ '"';
});
alert(tag);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" class="something" style="width:80%; display:inline-block">
Hello!
<div id="bar" class="something_else">
How are you?Hope you are doing well!
</div>
</div>
&#13;
答案 3 :(得分:0)
使用Array#reduce
let el = document.getElementById('foo');
let res = [].slice.call(el.attributes).reduce((a, c) => {
return a.concat(c.name + '="' + c.value + '"');
}, [el.tagName.toLowerCase()]).join(' ');
console.log(res)
&#13;
<div id="foo" class="something" style="width:80%; display:inline-block"></div>
&#13;