I know that it\'s faster to do the following:
var $header = $(\"#header\");
$header.css({color:\"#ff0000\"});
$header.find(\"a\").addClass(\"foo\");
<
Use ES6 template literals for multiple variables as selectors:
$(`${$header_elements}, ${$footer_elements}`).css('color','#ff0000');
Just use the add method:
$header_elements.add($footer_elements).css({color:'#ff0000'});
Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.
To keep the code simple and prevent code duplication I used a forEach
loop.
var $header_items = $("#header li");
var $footer_items = $("#footer li");
[$header_items, $footer_items].forEach(function($blockItems){
// do logic here
$blockItems.css('color', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header">
<h1>Header</h1>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</div>
<div id="footer">
<h1>Footer</h1>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</div>