Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit HTML inside text/template

I got multiple text/template scripts in my code, I want to be able to change the h1 tag in all of them using javascript (Jquery)

<script type="text/template">
    <h1>This should be replaced</h1>
    <p>Testing 123</p>
</script>

I don't want to create a new element from this template, I want to change the actual content of the template.

Here's what I've tried so far, which sadly doesn't return any results.

console.log($("script[type='text/template']"));

Really grateful for pointers!

like image 641
Tompina Avatar asked Jan 01 '26 00:01

Tompina


1 Answers

Since the h1 element is not part of your DOM you can create a new element, add your HTML to that element, manipulate it (using jquery) and then put the result back into the original script element:

t = $("script[type='text/template']")
container = $('<div/>').html(t.html())
container.find('h1').replaceWith('<h2>new content</h2>')
t.html(container.html())

console.log($("script[type='text/template']").html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/template">
    <h1>This should be replaced</h1>
    <p>Testing 123</p>
</script>
like image 117
Dekel Avatar answered Jan 02 '26 13:01

Dekel