[removed] Select all data-qa attributes on HTML Page

前端 未结 2 1192
渐次进展
渐次进展 2020-12-22 11:29

Using only JavaScript, without the use of JQuery etc, what is the most efficient way to select all attributes names that have a certain data attribute (let\'s say data-qa).<

相关标签:
2条回答
  • 2020-12-22 12:03

    For reference, below is essentially the core vanilla javascript functionality needed ...

    Using querySelectorAll, querySelector and getElementById should get you started.

    // get "data-qa" value by "id"
    var data = document.getElementById('id-test2').getAttribute('data-qa');
    console.log(data);
    
    // get "id" value by "data-qa"
    var data = document.querySelector('[data-qa="data-qa-test2"]').id;
    console.log(data);
    
    // get all elements with attribute "data-qa"
    var elems = document.querySelectorAll('[data-qa]');
    
    // get all "ids"
    var data = [];
    elems.forEach(function(elem){
      data.push(elem.id);
    });
    console.log(data);
    
    // get all "data-qa"
    var data = [];
    elems.forEach(function(elem){
      data.push(elem.getAttribute('data-qa'));
    });
    console.log(data);
    <div id="id-test" data-qa="data-qa-test"></div>
    <div id="id-test1" data-qa="data-qa-test1"></div>
    <div id="id-test2" data-qa="data-qa-test2"></div>
    <div id="id-test3" data-qa="data-qa-test3"></div>

    0 讨论(0)
  • 2020-12-22 12:18

    The code below works by getting all of the elements using document.querySelectorAll, mapping the elements to the values of the data attributes, and then filtering out the ones that are falsy or '0'.

    let getAllDataAttrs = name => Array.from(
        document.querySelectorAll(`[data-${name}]`)
      ).map(elem => elem.getAttribute(`data-${name}`))
      .filter(val => val && val !== '0');
    
    console.log(getAllDataAttrs('foo'));
    <p data-foo="0"></p><br/>
    <h6 data-foo="apple"></h6>
    <p data-foo="0"></p><br/>
    <h6 data-foo="book"></h6>
    <p data-foo="0"></p><br/>
    <h6 data-foo="car"></h6>

    0 讨论(0)
提交回复
热议问题