首页 > 解决方案 > CKEditor 5 按属性查找模型元素

问题描述

我的编辑器中存在一个自定义 html dom 元素:

<content id="1">
 <p>Paragraf is here and <a href="/url/to">link text</a> exists</p>
</content>

我想使用它的属性在模型中找到这个元素。我可以使用从根开始的递归方法找到它。但是有没有像 querySelectorAll 这样更简单的方法?

标签: ckeditorckeditor5

解决方案


我还没有找到一个开箱即用的帮助方法,但是如果有人只是在寻找他们可以使用的函数定义,试试这个:

function findDescendant (modelElement, predicate) {
  if (predicate(modelElement)) {
    return modelElement
  }
  if (modelElement.getChildren) {
    for (let child of modelElement.getChildren()) {
      const found = findDescendantByName(child, name)
      if (found) {
        return found
      }
    }
  }
}

...
...

const descendant = findDescendant(element, (element) => element.hasAttribute('foobar'))

推荐阅读