首页 > 解决方案 > 如何从 html5 标签字符串中提取属性

问题描述

我有一个字符串:

<input type="text" data-id="1" />

我想允许用户从这个 html5 输入标签字符串中提取属性。

像这样

from('<input type="text" data-id="1" />').extract("type")

我试过这个:

function from(str) {
    return {
        extract: function (attr) {
            return str.split(attr)
        }
    }
}

但这不起作用。

我怎样才能做到这一点?

仅使用 javascript。

标签: javascript

解决方案


这应该可以帮助您:

let x = (new DOMParser()).parseFromString('<input type="text" data-id="1" />', "text/xml");
x.firstChild.getAttribute("type"); // text

推荐阅读