she hates me
she hates me

Reputation: 1272

How to manipulate Template element with JQuery?

I'm trying to manipulate inside of <template> element with jQuery but unfortunately some functions like find() don't work for child elements.

How can I replace the text of .name class of this template and append it to inside of another html element?

<template id="conversationTemplate">
  <div class="card conversation mb-1">
    <div class="name">##name##</div>
  </div>    
</template>

Upvotes: 2

Views: 1027

Answers (3)

Rafael Mori
Rafael Mori

Reputation: 949

A simple solution we have here using just JQuery. Four lines, but with a few steps we can make it singleliner for those who prefer.

$(() => {
  const $templateTag = $('#conversationTemplate');
  const $clonedContent = $($('#conversationTemplate').html());
  $clonedContent.find('.name').html('other text here');
  $templateTag.wrap('<template id="conversationTemplate"></div>').parent().html($clonedContent);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<template id="conversationTemplate">
  <div class="card conversation mb-1">
    <div class="name">##name##</div>
  </div>    
</template>

Upvotes: 3

donohoe
donohoe

Reputation: 14133

You can do this in jQuery but you don't need to. This is plain javascript that will also just work.

var template = document.getElementById('conversationTemplate');
var html = template.innerHTML.replace('##name##', 'Jane');
var target = document.getElementById('the-other-element-you-mention');
target.innerHTML = html;

It does two things you asked:

  1. Gets template HTML and replaces the name.
  2. Updates another element with this new HTML.

Upvotes: 0

Thallius
Thallius

Reputation: 2619

You cannot use jQuery selector functions directly on a template. You need to parse this first.

var tpl = $('#conversationTemplate')[0].outerHTML;
$template = $($.parseXML(tpl)).contents();
console.log($template.find('.name').html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<template id="conversationTemplate">
    <div class="card conversation mb-1">
        <div class="name">##name##</div>
    </div>
</template>

Upvotes: 1

Related Questions