How to check if some element has attribute “name” starts with something, not “value”

后端 未结 3 948
刺人心
刺人心 2021-01-26 08:39

I\'m going to use various data attributes names start with for example \"data-mo-\".

Assume I have these elements:



        
3条回答
  •  没有蜡笔的小新
    2021-01-26 09:23

    A concise approach using ES6 is to select all elements in the document, then .filter by whether .some of the attribute names start with the string you're looking for:

    const moElements = [...document.querySelectorAll('*')]
      .filter(elm => [...elm.attributes].some(
        ({ name }) => name.startsWith('data-mo-')
      ));
    console.log(moElements);
    Title 1
    Title 2
    Title 3
    Title 4
    somethingElse

    Or, if you want to avoid constructing the intermediate arrays with spread, you can .call the array methods on the element / attribute collections instead:

    const moElements = Array.prototype.filter.call(
      document.querySelectorAll('*'),
      elm => Array.prototype.some.call(
        elm.attributes,
        ({ name }) => name.startsWith('data-mo-')
      )
    );
    console.log(moElements);
    Title 1
    Title 2
    Title 3
    Title 4
    somethingElse

提交回复
热议问题