0

I was trying to get jQuery Datatables work in my LWC. I have tried this: LWC is it Possible to Load the JQuery Plugin Datatables in a Lightning Web Component?

But I was not able to get it work. Everything went well until this line of code:
let dataTable = $(table).DataTable();
It actually removed the <table> element from the page.

Can anybody help me here? Thanks in advance!!!

Code here:

HTML

<template>
    <table lwc:dom="manual" class="example-table display" style="width:100%"></table>
</template>

JS

import { loadStyle, loadScript } from 'lightning/platformResourceLoader';

import jQuery from '@salesforce/resourceUrl/jQuery';
import DATATABLES_JS from '@salesforce/resourceUrl/DataTables_js';
import DATATABLES_CSS from '@salesforce/resourceUrl/DataTables_css';


renderedCallback() {
    if(firstTimeRender) {
        loadScript(this, jQuery).then(() => {

            console.log('Loaded JQUERY');

            loadStyle(this, DATATABLES_CSS).then(() => {

                console.log('Loaded Datatables CSS');

                loadScript(this, DATATABLES_JS).then(() => {

                    console.log('Loaded Datatables JS');
                    const table = 
                    this.template.querySelector('.example-table');
                    const columnHeaders = ['Id', 'Name'];

                    let columnHeaderHtml = '<thead><tr>';

                    columnHeaders.forEach(function(header) {
                        columnHeaderHtml += '<th>' + header + '</th>';
                    });

                    columnHeaderHtml += '</tr></thead>';

                    table.innerHTML = columnHeaderHtml;

                    let dataTable = $(table).DataTable(); // Here is when it went wrong 

                    this.recordsQueried.forEach(function(r) {
                        dataTable.row.add([
                            r.Id,
                            r.Name
                        ]);
                    }) 
                    dataTable.draw();



            })
        })
    })
}

}

4
  • 2
    Can anybody help me here? Not without seeing your code. Please edit your question to include the code you've tried so far. Commented Nov 13, 2019 at 18:40
  • Thanks for your advice! I have updated the question with my code. Commented Nov 13, 2019 at 19:42
  • Have you tried the main bit of the javascript outside of LWC? Commented Nov 13, 2019 at 22:03
  • Yes, it works outside LWC... Commented Nov 13, 2019 at 23:23

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.