10

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.

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man. The last option works for me and it seems not putting the data-header in quotation was my mistake.
2

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.

Comments

0
.attr 

is not allowed to add custom headers use

.data

instead.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.