1

My template involving parent div with attribute of data-template and child button with attribute of data-click:

<script type="text/html" id="containerTemplate">
    <div data-template="myTemplate">    
        <ul>      
          <li>
            <button type="button" data-click="done">
              <span>some text</span>
            </button>
          </li>
        </ul>
    </div>  
</script>

How can i select the button with the data-click="done"?

I've tried this

const doneBtn = document.querySelector('[data-template = myTemplate] [data-click = done]');
if (doneBtn) {
    //register some event listeners
}

But the doneBtn is returning null.

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
  • If you are using jQuery, you can use `.data()` (Source: https://api.jquery.com/data/) or you can use `$(selector).attr("data-click") === "done"` – Waleed Iqbal Jan 29 '18 at 08:34
  • If you are interested in doing it without jquery, follow this ... https://stackoverflow.com/questions/15912246/access-data-attribute-without-jquery – Waleed Iqbal Jan 29 '18 at 08:36
  • 1
    are you familiar with templates? you have to actually inject that script template in the DOM to be able to target it with querySelector – pumpkinzzz Jan 29 '18 at 09:54

1 Answers1

1

You put your html code in javascript tags that's why javascript was unable to access your html DOM. Try below code it will work.

<div data-template="myTemplate">    
    <ul>      
      <li>
        <button type="button" data-click="done">
          <span>some text</span>
        </button>
      </li>
    </ul>
</div> 


<script type="text/javascript">
 const doneBtn = document.querySelector('[data-template = myTemplate] [data-click = done]');
if (doneBtn) {
    //register some event listeners
    console.log($(doneBtn).html());
}
  </script>
Abdullah Shoaib
  • 416
  • 1
  • 5
  • 18