Search code examples
javascripthtmlselectors-api

Get element using querySelectorAll


I have the html tag as,

<div data-id='test'></div>

I need to get this element using

document.querySelectorAll('[data-id="test"]');

But the above code returns always empty array. Please help me in getting the element using querySelectorAll().


Solution

  • There shouldn't be any double quotes with your ID

    document.querySelectorAll('[data-id=test]');
    

    OR

    document.querySelectorAll('div[data-id=test]');
    

    And make sure you place this inside onload or make the JavaScript tag as defer="defer"