如何从html标签获取前缀名称

时间:2018-12-10 22:40:20

标签: javascript php regex

我有一些这样的输入html标签
输入:

<AvionToBuy>:
    text: root.avion[0] + ' ' + root.avion[1] + ' ' + str(root.avion[2]) + '$'
    background_color: [1, 0, 1, .5]
    on_release: print(root.avion)

是否有任何方法可以获取包含方案前缀``fx-''是来自该输入的方案标签的属性

我想做的就是得到这样的输出
输出:

<div fx-prop sc-alias="" fx-type="Organization"><div fx-name="Kirito">SAO <i fx-name="Asuna">World</i></div></div>

该解决方案可能使用php或javascript,但是我仍然没有得到答案

1 个答案:

答案 0 :(得分:3)

如果您知道属性名称,则可以将Element.getAttribute()方法与Element.attributes结合使用:

const elt = document.getElementsByTagName('div')[0];

const func = elt => {
  let res=[{}];
  for (let i=0; i<elt.attributes.length; i++) {
    let attrName = elt.attributes[i].name;
    if (attrName.substring(0,2)=='fx') {
      res[0][attrName.substring(3)] = elt.getAttribute(attrName);
    }
  }
  for (let i=0; i<elt.children.length; i++) {
    res.push(func(elt.children[i]));
  }
  return res;
}

console.log(func(elt));
<div fx-prop sc-alias="" fx-type="Organization">
  <div fx-name="Kirito">
    SAO
    <i fx-name="Asuna">
      World
    </i>
  </div>
</div>