Search code examples
javascripthtmlinnerhtmlgetelementbyid

inner element of <script> not recognized by document


I have a template <script> tag that is holding some HTML code and I want to replace the label text with a JS script.

<script type="text/template" id="element">
    <body>
        <label id="sub-element">Replace me</label>
    </body>
</script>

and right after it, I have some JavaScript:

<script> 
   let str = "Some text";
</script>

What would the best approach?

I've tried using document.getElementById("sub-element").innerHTML and it didn't do anything.

Thank you


Solution

  • Markup inside a script tag that's not interpreted to be JavaScript will be completely ignored. No #sub-element element exists in the DOM.

    You can use DOMParser to turn the content into a document, change it as needed, then turn the document back into text and replace it in the template:

    const template = document.querySelector('#element');
    const doc = new DOMParser().parseFromString(template.textContent, 'text/html');
    doc.querySelector('#sub-element').textContent = 'Some text';
    template.textContent = doc.body.outerHTML;
    console.log(template.textContent);
    <script type="text/template" id="element">
        <body>
            <label id="sub-element">Replace me</label>
        </body>
    </script>

    But if you're planning on doing any nontrivial amount of something like this, I'd highly recommend using a framework instead to insert content into a template, instead of using manual DOM manipulation. For example, with React, you could do something like:

    const SomeLabel = ({ content }) => <label id="sub-element">{content}</label>;
    const App = () => {
        return <SomeLabel content="Some Text" />;
    };
    ReactDOM.render(<App />, document.querySelector('.react'));
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <div class='react'></div>