0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【jQuery】DataTablesで`<sample>`のような文字列をHMTLタグとして認識させずに表示させる方法

Posted at

概要

jQueryのDataTablesを利用中のサイトで<sample>のような<>で括られた文字列を扱うと、HMTLタグとして認識されてしまい表示されない事象を確認しました。こちらの原因と解決方法を紹介します。

原因

原因は、データを適切にエスケープしていなかったためでした。
jQueryのtextメソッドを使用してデータをエスケープすることができます。

以下、サンプルコードです。

$(document).ready(function() {
    $('#example').DataTable({
        "ajax": {
            "url": "/your-data-url/",
            "dataSrc": ""
        },
        "columns": [
            {
                "data": "sample_data",
                "render": function(data) {
                    return $('<div/>').text(data).html();
                }
            },
            // 他のカラム設定
        ]
    });
});

render関数は、データを表示する前にカスタム処理を行うために使用できます。

return $('<div/>').text(data).html();がjQueryを使用してデータをエスケープしている箇所。
$('<div/>').text(data)は、データをテキストとして<div>要素に設定し、.html()はエスケープされたHTMLを取得します。

これにより、<sample>といった文字列がDatatables上に正常に表示されました。

ちなみに、text()と似たメソッドにhtml()があります。
ただ、

return $('<div/>').html(data).html();

のようにすると、<sample>はDataTablesに表示されませんでした。
これは、html()だとエスケープされずにHTMLタグとして認識するためです。
<p>タグなどを実際にタグ要素として認識させたい場合には活用できます(今回はただの文字列として扱いたいのでtext()の方でOK)。

参考記事

公式ドキュメント

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?