Search code examples
htmldomtagsqueryselector

How to select a div element that does not have a class?


Sample HTML Element
<div data-testid="Custom Data Test"> 
  • The above div does not have a class inside.
  • How do I access, "data-testid" (which selector should I use)

Solution

  • You can use querySelector() or querySelectorAll() and select by attribute like this:

    const div = document.querySelector('div[data-testid="Custom Data Test"]');
    div.textContent = "blah";
    
    const divs = document.querySelectorAll('div[data-testid]');
    divs.forEach( (e,i) => e.textContent = e.textContent + " this is div number " + i + " and data-testid attribute is " + e.dataset.testid);
    Sample HTML Element
    <div data-testid="Custom Data Test"></div>
    
    <div data-testid="Custom Data Test 2"></div>
    <div data-testid="Custom Data Test 3"></div>