Search code examples
javascriptsimple-html-dom

get value from attribute "pseudo-element" using Javascript


I got DOM element which has many Div tags inside, without any class or ID. All I want is to get values from the div Attribute "data-as-pseudo-element" using Javascript (no JQuery or any other library).

The result should be:

Hello How Are You
ABC
XYZ

  <div role="none" >
      <div
          data-as-pseudo-element="Hello How Are You" style="position: relative;display: inline;"
      ></div>
      
       
      <div
          data-as-pseudo-element="ABC" style="position: relative;display: inline;"
      ></div>
      
       
      <div
          data-as-pseudo-element="XYZ" style="position: relative;display: inline;"
      ></div>
  
  </div>
  
  

Thanks in advance!


Solution

  • Easy to do using querySelectorAll to find the elements, and dataset to extract the value:

    for (div of document.querySelectorAll('div[data-as-pseudo-element]')) {
      console.log(div.dataset.asPseudoElement)
    }
    <div role="none" >
          <div
              data-as-pseudo-element="Hello How Are You" style="position: relative;display: inline;"
          ></div>
          
           
          <div
              data-as-pseudo-element="ABC" style="position: relative;display: inline;"
          ></div>
          
           
          <div
              data-as-pseudo-element="XYZ" style="position: relative;display: inline;"
          ></div>
      
      </div>