LoginSignup
7
4

More than 5 years have passed since last update.

templateタグをjQueryで操作しようとしたらハマった話

Posted at

jQueryを使ってtemplateタグをクローンしようとしたら中々にハマったのでメモ。

結論

一度HTML文字列として取得してからjQueryオブジェクトにする

var clone = $($('#productrow').html());

これはダメ

templateタグからは直接操作できなかった。。

var clone = $('#productrow *');
var clone = $('#productrow').children();

検証用メモ

HTMLはこちらを使用
https://qiita.com/naoqoo2/items/771b3b19b04b1a99c300


<script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>

<script>
if ('content' in document.createElement('template')) {

  var clone = $($('#productrow').html());
  $('td', clone).eq(0).text('0384928528');
  $('td', clone).eq(1).text('Acme Kidney Beans');
  $('tbody').append(clone);

}
</script>
7
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4