Nuru Salihu
Nuru Salihu

Reputation: 4928

JQuery: Create new element with data attribute

Please i am having difficulty creating the 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 through like 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);
}

The problem is

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

does not add my data-header property. I tried adding it like

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

And it throws error.

I tried

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

as explain Here as well and it isn't adding. Please how do i achieve or add the property dynamically ? Any help or suggestion would be appreciated.

Upvotes: 10

Views: 6435

Answers (3)

BenG
BenG

Reputation: 15154

wrap data-header in ' :-

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

Another option is to set the 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 only be available after you append.

Though you should use .data('header', 'value'); to set data.

Upvotes: 13

lyRx
lyRx

Reputation: 1

.attr 

is not allowed to add custom headers use

.data

instead.

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

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

The following code work fine and add the data attribute to the element with class className :

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

But in your case you can add rowElement because the variable is not added to the DOM :

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

Note : Better to use data instead of attr when you want set or get data attributes.

Hope this helps.

Upvotes: 2

Related Questions