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.

3
  • If you are using jQuery, you can use .data() (Source: api.jquery.com/data) or you can use $(selector).attr("data-click") === "done" Commented Jan 29, 2018 at 8:34
  • If you are interested in doing it without jquery, follow this ... stackoverflow.com/questions/15912246/… Commented Jan 29, 2018 at 8: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 Commented Jan 29, 2018 at 9:54

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.