Reputation: 1111
As the title says is there a way I can clone two elements and store them in one variable instead of creating a separate variable. Tried using &&
to get both elements but didn't work
var menu = $('a[href$="/items"]').clone() && $('a[href$="/items"]').next().clone();
$('.footer .footer-menu').append(menu);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a href="aim/items">Item </a>
<ul>
<li>item one</li>
</ul>
</li>
</ul>
<div class="footer">
this is a footer
<div class="footer-menu">
</div>
</div>
Upvotes: 2
Views: 117
Reputation: 12181
Here you go with an array
solution https://jsfiddle.net/wrdp548d/
var menu = [];
menu.push($('a[href$="/items"]').clone());
menu.push($('a[href$="/items"]').next().clone());
$('.footer .footer-menu').append(menu);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a href="aim/items">Item </a>
<ul>
<li>item one</li>
</ul>
</li>
</ul>
<div class="footer">
this is a footer
<div class="footer-menu">
</div>
</div>
Another way
var menu = [];
menu.push($('a[href$="/items"]').clone());
menu.push($('a[href$="/items"]').next().clone());
$.each(menu, function(i){
$('.footer .footer-menu').append(menu[i]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a href="aim/items">Item </a>
<ul>
<li>item one</li>
</ul>
</li>
</ul>
<div class="footer">
this is a footer
<div class="footer-menu">
</div>
</div>
Here you go with an object solution https://jsfiddle.net/wrdp548d/1/
var menu = {
clone1: $('a[href$="/items"]').clone(),
clone2: $('a[href$="/items"]').next().clone()
};
for(var key in menu){
$('.footer .footer-menu').append(menu[key]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a href="aim/items">Item </a>
<ul>
<li>item one</li>
</ul>
</li>
</ul>
<div class="footer">
this is a footer
<div class="footer-menu">
</div>
</div>
Hope this will help you.
Upvotes: 1
Reputation: 4650
A simple variable can only hold one value. If you need to hold more than one you either use an array or object.
Using array:
var clone1 = $('a[href$="/items"]').clone();
var clone2 = $('a[href$="/items"]').next().clone();
var menu = [clone1, clone2];
or object:
var clone1 = $('a[href$="/items"]').clone();
var clone2 = $('a[href$="/items"]').next().clone();
var menu = {'clone1': clone1, 'clone2': clone2};
Then you're going to have to access the values by looping thru it or directly accessing it via array index menu[0]
or object properties menu.clone1
menu[clone1]
Upvotes: 1