Reputation: 47
There are 2 arrays with variables, you need to combine them, create button elements with the btn-menu class, data element category (with a variable from the array), and text from the array.
let category = ['Pizza 🍕', 'Rolls 🍣', 'Sets 🍱', 'Hot dish🥘', 'Salads🥗'];
let slug_id = ['pizza', 'rolls', 'sets', 'hot-dish', 'salads'];
The order of the first and second arrays corresponds to the content, that is, Pizza 🍕(0) and pizza(0) need to output all these elements to the HTML nav object with the container class.
You should get a horizontal menu with buttons:
<nav class="container">
<button class="btn-menu ripple-btn" category="pizza">Pizza 🍕</button>
<button class="btn-menu ripple-btn" category="rolls">Rolls 🍣</button>
<button class="btn-menu ripple-btn" category="sets">Sets 🍱</button>
<button class="btn-menu ripple-btn" category="hot-dish">Hot dish🥘</button>
<button class="btn-menu ripple-btn" category="salads">Salads 🥗</button>
</nav>
You need the code in js or jQuery. Please help me solve the problem :)
Here's what I tried:
var category = ['Pizza 🍕', 'Rolls 🍣', 'Sets 🍱', 'Hot dish🥘', 'Salads🥗'];
var slug_id = ['pizza', 'rolls', 'sets', 'hot-dish', 'salads'];
var nav = $('.container');
for (var i = 0; i < category.length; i++) {
var btn = $('<button/>');
var class_btn = $(btn).attr('class','btn-menu ripple-btn');
var text_btn = $(class_btn).text(category[i]);
}
$(btn).appendTo(nav);
Upvotes: 0
Views: 126
Reputation: 28522
As you are already iterating through the array and length of both array are same simply you can use $(btn).attr('category', slug_id[i]);
this will add array value at i
position on every iterating inside button.
Demo Code :
var category = ['Pizza 🍕', 'Rolls 🍣', 'Sets 🍱', 'Hot dish🥘', 'Salads🥗'];
var slug_id = ['pizza', 'rolls', 'sets', 'hot-dish', 'salads'];
var nav = $('.container');
for (var i = 0; i < category.length; i++) {
var btn = $('<button/>');
$(btn).attr('class', 'btn-menu ripple-btn');
$(btn).text(category[i]);
$(btn).attr('category', slug_id[i]); //use this to add attribute with value from array
$(btn).appendTo(nav); //add button created inside nav
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="container">
</nav>
Upvotes: 1