1

I have an html element which is created in JavaScript.
This element should also save one object as a data- attribute and then get converted to pure html.
My problem is that the data- attribute vanishes after accessing the prop("outerHTML").

Here is what I mean:

let obj = $("<i>TEST</i>");
obj.data("key", "value");
let html = obj.prop("outerHTML");
console.log("DATA: " + obj.data("key")); //gives value
console.log("HTML: " + html); //gives <i>TEST</i>   

I also tried to directly enter the data- attribute, but the quotes a making trouble.

I tried:

let dataJSON = JSON.stringify(data);
let obj = $('<i data-test=' + dataJSON + '</i>'

My goal is to generate a dataTable cell which needs to contain some data to handle clicks on it. The whole thing looks like this:

columns: [
   data: "notice_id", render: function (data, type, row) {
      let html = $('<i class="edit-button fas fa-pencil-alt"></i>');
      html.data("notice", row);
      return html.prop("outerHTML");
      }]

edit:
I should have written that I know, that jQuery doesn't really alter the data- attribute. I somehow hoped that it would add it anyways when I access the outer html.
However, the linked question doesn't really give an answer on how to make it better (except writing it directly which causes problems with other than simple string data).

Adriano
  • 3,788
  • 5
  • 32
  • 53
TimSch
  • 1,189
  • 1
  • 12
  • 27
  • 1
    Possible duplicate of [JQuery .data() not working?](https://stackoverflow.com/questions/25876274/jquery-data-not-working) – maximelian1986 Mar 16 '19 at 19:31

1 Answers1

1

You can use the createdCell callback if you want more post processing, and enrich the <i> with data() in there:

columns: [{
  data: "notice_id", 
  render: function(data, type, row) {
    //no need for constructing jQuery instances here
    return '<i class="edit-button fas fa-pencil-alt"></i>'
  },
  createdCell: function(td, cellData, rowData, row, col) {
    $('i', td).data('notice', rowData)
  }
}]
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • Thanks man! You helped me even more, because I also found the "`createdRow`" callback which helped me to reduce my code even more. – TimSch Mar 17 '19 at 12:50