JQuery: create a new element with data attribute

I find it difficult to create a flexbox script below dynamically.

<div class="Table-row">
    <div class="Table-row-item u-Flex-grow2" data-header="Header1">row2 col1</div>
    <div class="Table-row-item" data-header="Header2">row2 col2</div>
    <div class="Table-row-item" data-header="Header3">row2 col3</div>
    <div class="Table-row-item" data-header="Header4">row2 col4</div>
    <div class="Table-row-item u-Flex-grow3" data-header="Header5">row2 col5</div>
    <div class="Table-row-item" data-header="Header6">row2 col6</div>
    <div class="Table-row-item" data-header="Header7">row2 col7</div>
  </div>

In my jQuery i loop as below.

for (var i = 0 ; i < data.length ; i++){
   var className = metadata[i].toLowerCase().replace(/\s/g, "-") + " Table-row-item";
   var rowElement = $("<div></div>", {class: className, text: data[i]});

   $('.'+className).prop('data-header', 'value');
   rowElement.appendTo($tr);
}

Problem

$('.'+className).prop('data-header', 'value');

does not add my property data-header. I tried to add it as

$("<div></div>", {class: className, text: data[i], data-header :'value'})

And that causes an error.

I tried

$('.'+className).attr('data-header', 'value');

how to explain here is also not added. How can I achieve or add a property dynamically? Any help or suggestion would be appreciated.

+4
source share
3 answers

wrap data-headerin ': -

$("<div></div>", { 'class': className, 'text': data[i], 'data-header' :'value'});

Another option is to install rowElement: -

var rowElement = $("<div></div>", {class: className, text: data[i]});
rowElement.prop('data-header', 'value');

or

var rowElement = $("<div></div>", {class: className, text: data[i]}).prop('data-header', 'value');

$('.'+className)will be available only after append.

Although you should use .data('header', 'value');to install data.

+4
source

data className:

$('.'+className).attr('data-header', 'value');

rowElement, ​​ DOM:

$(rowElement).find('.'+className).attr('data-header', 'value');

: data attr, set get.

, .

+1
.attr 

not allowed to add custom headers use

.data

instead of this.

http://api.jquery.com/jQuery.data/

0
source

Source: https://habr.com/ru/post/1614943/


All Articles