如何创建以下对象:
{
element: "div",
class: ["OneClass", "TwoClass"],
text: "This is some text"
}
来自以下HTML:
<div class="OneClass TwoClass">This is some text</div>
答案 0 :(得分:1)
您可以尝试以下方式:
var el = document.querySelector('div');
var obj = {};
var clsList = el.classList.value.split(' ')
obj.element = el.tagName.toLowerCase();
obj.class = clsList;
obj.text = el.textContent
console.log(obj);
&#13;
<div class="OneClass TwoClass">This is some text</div>
&#13;
答案 1 :(得分:0)
使用jQuery:
var html = '<div class="OneClass TwoClass">This is some text</div>';
var el = $(html);
var obj = {
class: el.attr("class").split(/ /),
text: el.text(),
element: el.prop("tagName")
};
console.log(JSON.stringify(obj));
输出:
{"class":["OneClass","TwoClass"],"text":"This is some text","element":"DIV"}