Home > Enterprise >  How to manipulate Template element with JQuery?
How to manipulate Template element with JQuery?

Time:01-07

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 >
    <div >##name##</div>
  </div>    
</template>

CodePudding user response:

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 >
    <div >##name##</div>
  </div>    
</template>

CodePudding user response:

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 >
        <div >##name##</div>
    </div>
</template>

CodePudding user response:

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.
  •  Tags:  
  • Related