<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Quick Tips &#8211; The Web Developer Guide</title>
	<atom:link href="https://thewebdeveloperguide.com/category/quick-tips/feed/" rel="self" type="application/rss+xml" />
	<link>https://thewebdeveloperguide.com</link>
	<description>A Developers Guide to Web Develoment</description>
	<lastBuildDate>Wed, 29 Mar 2023 07:58:51 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.2</generator>
	<item>
		<title>How to Use Javascript to Add to an Array</title>
		<link>https://thewebdeveloperguide.com/how-to-use-javascript-to-add-to-an-array/</link>
		
		<dc:creator><![CDATA[Kris Barton]]></dc:creator>
		<pubDate>Wed, 10 Apr 2019 07:50:13 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Frontend]]></category>
		<category><![CDATA[Quick Tips]]></category>
		<category><![CDATA[add to array]]></category>
		<category><![CDATA[array.concat()]]></category>
		<category><![CDATA[array.push()]]></category>
		<category><![CDATA[array.splice()]]></category>
		<category><![CDATA[array.unshift()]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[javascript add to array]]></category>
		<category><![CDATA[javascript arrays]]></category>
		<category><![CDATA[javascript methods]]></category>
		<guid isPermaLink="false">https://www.thewebdeveloperguide.com/?p=116</guid>

					<description><![CDATA[Did you know there are at least 4 ways to add data to an array using Javascript? Check it out.]]></description>
										<content:encoded><![CDATA[
<p>Do you want to use Javascript to add data to an array but are wondering what the method is? <g class="gr_ gr_5 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="5" data-gr-id="5">Well</g> there are a number of ways you can do it, but the <strong><em>array.push()</em></strong>, <strong><em>array.unshift(),</em></strong> <strong><em>array.splice()</em></strong> or the <em><strong>array.</strong><g class="gr_ gr_256 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="256" data-gr-id="256"><strong>concat</strong></g><strong>()</strong> </em>methods are probably the ones you’re looking for.<br></p>



<p>Let’s examine these Javascript methods and see what each of them can do.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" width="500" height="500" src="https://www.thewebdeveloperguide.com/wp-content/uploads/2019/04/javascript-add-to-array.jpg" alt="There are 4 ways you can Use Javascript to add to array meme" class="wp-image-118" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2019/04/javascript-add-to-array.jpg 500w, https://thewebdeveloperguide.com/wp-content/uploads/2019/04/javascript-add-to-array-150x150.jpg 150w, https://thewebdeveloperguide.com/wp-content/uploads/2019/04/javascript-add-to-array-300x300.jpg 300w" sizes="(max-width: 500px) 100vw, 500px" /></figure></div>


<h2 class="wp-block-heading">Using Javascript to Add to an Array with Array Push</h2>



<p>The <strong><em>array.push() </em></strong>Javascript method allows you to easily add <g class="gr_ gr_4 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-del replaceWithoutSep" id="4" data-gr-id="4">a value</g> <strong><em>to the end of an array</em></strong>. Here’s how it works: </p>



<pre class="wp-block-preformatted"><strong>let items = [‘item1’, ‘item2’];<br>items.push(‘item3’); <br>//Output: item1, item2, item3</strong><br></pre>



<p>As you can see from the example above, adding a value to the array is as simple as adding the <strong><em>.push()</em></strong> method to your declared array variable and placing the value you want to add inside it. <br></p>



<p>It really is that simple.<br></p>



<p>But what if you wanted to use Javascript to add multiple items to an array? The <strong><em>array.push()</em></strong> method can totally do that too. </p>



<pre class="wp-block-preformatted"><strong>let items = [‘item1’, ‘item2’];<br>items.push(‘item3’, ‘item4’); <br>//Output: item1, item2, item3, &nbsp;‘item4’</strong><br></pre>



<p>Pretty easy, right? Let’s take a look at the <strong><em>array.unshift()</em></strong> Javascript method in action. </p>



<h2 class="wp-block-heading">Using Javascript to Add to an Array with Array Unshift</h2>



<p>The <strong><em>array.unshift()</em></strong> Javascript method is the polar opposite of <strong><em><g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="6" data-gr-id="6">array</g>.push()</em></strong>, allowing you to add values to the start of any array. Here’s how it works: </p>



<pre class="wp-block-preformatted"><strong>let items = [‘item1’, ‘item2’];<br>items.unshift(‘item3’); <br>//Output: item3, item1, item2</strong><br></pre>



<p>As you see from the example above, the <strong><em>array.unshift()</em></strong> method works exactly like the <strong><em>array.push()</em></strong> method. You attached the <strong><em>.unshift()</em></strong> method to our array variable and then place the value we want to add to the array inside it.<br></p>



<p>Again, super simple to use.<br></p>



<p>And like the <strong><em>array.push()</em></strong> Javascript method, <strong><em>array.unshift()</em></strong> allows for multiple items to be added to the start of the array:</p>



<pre class="wp-block-preformatted"><strong>let items = [‘item1’, ‘item2’];<br>items.push(‘item3’, ‘item4’); <br>//Output: item3, item4, item1, item2</strong><br></pre>



<h2 class="wp-block-heading">Using Javascript to Add to an Array with Array Splice</h2>



<p>But what if you wanted to add a value to an array, but in a <em>specific</em> place? Well, you could use the <strong><em>array.splice()</em></strong> Javascript method to accomplish that. <br></p>



<p>With <strong><em>array.splice()</em></strong> you can add values to an array, but you could also replace items too.<br></p>



<p>The syntax of the Javascript method is this:<br></p>



<p>array.splice(index, howmany, newvalues);<br></p>



<p>It breaks down like this:<br></p>



<ul>
<li>The index refers to the location within the array where you want to place any new items.</li>



<li>The howmany refers to the number of items you’d like to replace (0 means you remove nothing just add items).</li>



<li> The newvalues refers to any new values you’d like to add to the array. </li>
</ul>



<p>So for example, let’s say I have an array like this:</p>



<pre class="wp-block-preformatted"><strong>let items = ['item1', 'item2', 'item4', 'item5'];</strong> <br></pre>



<p>And I want to add a value of ‘item3’ in between ‘item2’ and ‘item4’. Then you would do this:</p>



<pre class="wp-block-preformatted"><strong>items.splice(2, 0, 'item3');<br>//Output item1, item2, item3, item4, item5</strong><br></pre>



<p>But what if I wanted to add that new value into the array, but remove the last 2 items? Then this would do the job:</p>



<pre class="wp-block-preformatted"><strong>let items = ['item1', 'item2', 'item4', 'item5'];<br>items.splice(2, 2, 'item3');<br>//Output item1, item2, item3</strong><br></pre>



<p>Of course, using the <strong><em>array.splice()</em></strong> Javascript method, you’re reliant on already <em>knowing</em> what the index is of the value you want to include.</p>



<h3 class="wp-block-heading">Splicing Into an Array at a Specific Place Based on an Array Value</h3>



<p>What if you didn’t know the index of where you wanted to splice in a new value? What if you wanted to add the value ‘item3’ after ‘item2’, without knowing where in the array ‘item2’ actually is?<br></p>



<p>Well, we could do a for loop to help us out with that:</p>



<pre class="wp-block-preformatted"><strong>let items = ['item1', 'item2', 'item4', 'item5'];<br>let position = 0;<br><br>for(let i = 0; i &lt; items.length; i++) {<br> &nbsp;&nbsp;&nbsp;if(items[i] === 'item2') {<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;position = i+1;<br> &nbsp;&nbsp;&nbsp;}  <br>} <br><br>items.splice(position, 0, 'item3');<br><br>//output of items is item1, item2, item3, item4, item5;</strong><br></pre>



<p>As you can see from the example above, I’m setting up two variable first, the array itself and a placeholder variable which will store the position in the array we’re going to include our new value.<br></p>



<p>Then, we loop through the array using the Javascright <strong><em>.length</em></strong> function and standard increment variable. Inside the loop, we’re access each item of the array and checking for our item2 value. When our value has been found, set our position variable to be the next item. <br></p>



<p>We’re doing this because we want to insert our item <em>after </em>‘item2’ &#8211; if we wanted to insert it before ‘item2’, we wouldn’t need to increment the iteration number by 1 to mark the position.<br></p>



<p>Then, outside the loop, we’re splicing the array. We’re using the position value we obtained with the loop as the index where we want the splice to happen, we’re setting a remove value of 0 because in this case we don’t want to cut any values out of the array and finally we’re declaring what value we’d like to insert. </p>



<h2 class="wp-block-heading">Using Javascript to Combine Arrays</h2>



<p>What if the value we’re trying to add to the array is actually another array? What do we do then?<br></p>



<p>Then we use the <strong><em>array.<g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="5" data-gr-id="5">concat</g>() </em></strong>Javascript Method. It works like this:</p>



<pre class="wp-block-preformatted"><strong>let arr1 = ['item1', 'item2'];<br>let arr2 = ['item3', 'item4'];<br><br>let items = arr1.concat(arr2);<br>//Output of items is: item1, item2, item3, item4.<br>//Output for arr1 is: item1, item2.<br>//Output for arr2 is: item3, item4.</strong><br></pre>



<p>Combining arrays in Javascript is as simple as the above example and much like other examples of adding values to arrays, more than 2 arrays can be combined.<br></p>



<p>Like this:</p>



<pre class="wp-block-preformatted"><strong>let arr1 = ['item1', 'item2'];<br>let arr2 = ['item3', 'item4'];<br>let arr3 = ['item5', 'item6'];<br>let arr4 = ['item7', 'item8'];<br><br>let items = arr1.concat(arr2, arr3, arr4);<br>//Output of items is: item1, item2, item3, item4, item5, item6, item7, item8.<br>//Output for arr1 is: item1, item2.<br>//Output for arr2 is: item3, item4.<br>//Output for arr3 is: item5, item6.<br>//Output for arr4 is: item7, item8.</strong><br></pre>



<p>Pretty cool and and easy stuff, right?<br></p>



<p>The <strong><em>array.concat()</em></strong> Javascript function works by create a new array based on all the arrays combined. It places the array items in the newly create array the order in which they’re included. <br></p>



<p>So what that means is because we declare <strong><em>arr1 </em></strong>as the starting array, the values for the new array will begin whatever values were held with the <strong><em>arr1</em></strong> array. <br></p>



<p>To demonstrate what I mean by this, let’s change up the code a little:</p>



<pre class="wp-block-preformatted"><strong>let arr1 = ['item1', 'item2'];<br>let arr2 = ['item3', 'item4'];<br>let arr3 = ['item5', 'item6'];<br>let arr4 = ['item7', 'item8'];<br><br>let items = arr2.concat(arr1, arr3, arr4);<br>//Output would be: item3, item4, item1, item2, item3, item4, item5, item6, item7, item8.</strong><br></pre>



<p>The output changes because in this example we’re starting with <strong><em>arr2</em></strong> which contains values ‘item3’ and ‘item4’.<br></p>



<p>Equally, if we change the order in which we list the arrays within the concat function we’d get a different output.</p>



<pre class="wp-block-preformatted"><strong>let arr1 = ['item1', 'item2'];<br>let arr2 = ['item3', 'item4'];<br>let arr3 = ['item5', 'item6'];<br>let arr4 = ['item7', 'item8'];<br><br>let items = arr2.concat(arr3, arr4, arr1);<br>//Output would be: item3, item4, item3, item4, item5, item6, item7, item8, item1, item2.</strong><br></pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p>With Javascript there are a number of ways you can add <g class="gr_ gr_17 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-del replaceWithoutSep" id="17" data-gr-id="17">a value</g> (or values) to <g class="gr_ gr_5 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="5" data-gr-id="5">array</g>, it really just depends on how you <em>want</em> to add those values to your array and how complex it needs to be.</p>



<p>If you need to know more information about removing values from an array, then I do recommend you check out <a href="https://www.thewebdeveloperguide.com/javascript-remove-from-array/">our Javascript Remove from Array article</a>.</p>



<p>For more information about everything we’ve discussed above, check out the further reading below.</p>



<h2 class="wp-block-heading">Further Reading:</h2>



<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push</a></li>



<li><a href="https://www.w3schools.com/jsref/jsref_push.asp" target="_blank" rel="noopener">https://www.w3schools.com/jsref/jsref_push.asp</a></li>



<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift</a></li>



<li><a href="https://www.w3schools.com/jsref/jsref_unshift.asp" target="_blank" rel="noopener">https://www.w3schools.com/jsref/jsref_unshift.asp</a></li>



<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice</a></li>



<li><a href="https://www.w3schools.com/jsref/jsref_splice.asp" target="_blank" rel="noopener">https://www.w3schools.com/jsref/jsref_splice.asp</a></li>



<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat</a></li>



<li><a href="https://www.w3schools.com/jsref/jsref_concat_array.asp" target="_blank" rel="noopener">https://www.w3schools.com/jsref/jsref_concat_array.asp</a> </li>
</ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Javascript Get Element By Class</title>
		<link>https://thewebdeveloperguide.com/javascript-get-element-by-class/</link>
		
		<dc:creator><![CDATA[Kris Barton]]></dc:creator>
		<pubDate>Fri, 05 Apr 2019 14:18:15 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Frontend]]></category>
		<category><![CDATA[Quick Tips]]></category>
		<category><![CDATA[get element by class]]></category>
		<category><![CDATA[get html elem]]></category>
		<category><![CDATA[getelementsbyclassname]]></category>
		<category><![CDATA[html elements]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[queryselector]]></category>
		<category><![CDATA[queryselectorall]]></category>
		<guid isPermaLink="false">https://www.thewebdeveloperguide.com/?p=112</guid>

					<description><![CDATA[Want to use JS to get an element by a class name? There are a couple of ways to do that - here's how!]]></description>
										<content:encoded><![CDATA[
<p>Want to use Javascript to get an element by its class? There are a couple of ways you can do that:<br></p>



<ul>
<li>getElementsByClassName()</li>



<li>querySelectorAll()</li>
</ul>



<p>But there are a few things you might want to consider before you implement either of these methods.<br></p>



<p>Let’s take a closer look.</p>



<h2 class="wp-block-heading">Using Javascript to Get an Element by Class</h2>



<p>The first way to use Javascript to get an element by class is to the <em><strong>getElementsByClassName</strong></em> method.</p>



<p>This method is used to get a group of elements by a particular class name. All elements, regardless of type, will be returned in an array-like object which can be accessed in a variety of ways.<br></p>



<p>Elements can then be accessed how you would normally access arrays in javascript &#8211; directly or dynamically, depending on your requirements.</p>



<h3 class="wp-block-heading">Why a Group of Elements and Not Just One?</h3>



<p>The <strong><em>getElementsByClassName</em></strong> Javascript method returns a group of elements in an array object rather than just one because classes are designed to be used multiple times on any given webpage and are used as such.</p>



<p><br></p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" loading="lazy" width="593" height="421" src="https://www.thewebdeveloperguide.com/wp-content/uploads/2019/04/javascript-get-element-by-class.jpg" alt="Use Javascript to get elements by class - select all the elements" class="wp-image-113" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2019/04/javascript-get-element-by-class.jpg 593w, https://thewebdeveloperguide.com/wp-content/uploads/2019/04/javascript-get-element-by-class-300x213.jpg 300w" sizes="(max-width: 593px) 100vw, 593px" /></figure></div>


<p>If you <em>know</em> there will always be one identifier for one element, then it would be better to use the ID attribute to access the element with the <strong><em>getElementById</em></strong> Javascript method. Or you could also use custom Data Attributes and use the <strong><em>querySelector</em></strong> Javascript method to access the element.<br></p>



<p>But what if you’re dealing with dynamic data? What if you don’t <em>know</em> how many elements there are? What if there could be one element or many elements and you need to anticipate that?<br></p>



<p>In this scenario, the <strong><em>getElementsByClassName</em></strong> Javascript method is absolutely an acceptable way to do so. <br></p>



<p>So let’s take a look at it in action.</p>



<h3 class="wp-block-heading">Using get Elements By Class Name Javascript method to get an element by class</h3>



<p>This is the scenario: we have 4 divs with the same class and we want to collect them together to be able to access them.<br></p>



<p>Here’s what the divs look like:</p>



<pre class="wp-block-preformatted">&lt;div class="item"&gt;Item 1&lt;/div&gt;<br>&lt;div class="item"&gt;Item 2&lt;/div&gt;<br>&lt;div class="item"&gt;Item 3&lt;/div&gt;<br>&lt;div class="item"&gt;Item 4&lt;/div&gt; <br></pre>



<p>Here’s how we collect them using getElementsByClassName:<br></p>



<pre class="wp-block-preformatted">const items = document.getElementsByClassName('item');<br></pre>



<p>If we were to console log the items variable, we’d get the following output:<br></p>



<pre class="wp-block-preformatted">HTMLCollection(4) [div.item, div.item, div.item, div.item]</pre>



<pre class="wp-block-preformatted">0: div.item<br>1: div.item<br>2: div.item<br>3: div.item<br>length: 4<br>__proto__: HTMLCollection<br></pre>



<p>As you can see, this function has collected all of our elements with the item class together and output them into an array. Now, we can access the collections like we would an array:<br></p>



<p>We have access to the the length property, so we can count how many elements on the page have the item class:<br></p>



<pre class="wp-block-preformatted">items.length;<br>//Output is 4<br></pre>



<p>Like any array, we can access any of the items directly:<br></p>



<pre class="wp-block-preformatted">Items[0]<br>//Output is: &lt;div class="item"&gt;Item 1&lt;/div&gt;<br></pre>



<p>Or we can loop through the array:<br></p>



<pre class="wp-block-preformatted">for(let i = 0; i &lt; items.length; i++) {<br>console.log(items[i]);<br>}<br>//Output is:&lt;div class="item"&gt;Item 1&lt;/div&gt; &lt;div class="item"&gt;Item 2&lt;/div&gt; &lt;div class="item"&gt;Item 3&lt;/div&gt; &lt;div class="item"&gt;Item 4&lt;/div&gt;</pre>



<h3 class="wp-block-heading">Multiple Class Names</h3>



<p>But there’s a little more cool functionality to the <strong><em>getElementsByClassName</em></strong> that you might not be aware of: the method accepts multiple class names.<br></p>



<p>So imagine that you have a set of elements with the same class, but you wanted to filter elements out by a second class. <br></p>



<p>Take these elements for example:<br></p>



<pre class="wp-block-preformatted">&lt;div class="item dogs"&gt;Item 1&lt;/div&gt;<br>&lt;div class="item cats"&gt;Item 2&lt;/div&gt;<br>&lt;div class="item fish"&gt;Item 3&lt;/div&gt;<br>&lt;div class="item fish"&gt;Item 4&lt;/div&gt;<br></pre>



<p>It’s pretty much the same as before, but each element has a second class &#8211; an animal class. Let’s say we wanted to select all the elements that have the item class that also have the fish class.<br></p>



<p>We’d do this:<br></p>



<pre class="wp-block-preformatted">const filterItems = document.getElementsByClassName('item fish');<br>//Output: &lt;div class="item fish"&gt;Item 3&lt;/div&gt; &lt;div class="item fish"&gt;Item 4&lt;/div&gt;<br></pre>



<p>Now let’s say we altered our elements to add a class for the animals that are still currently on sale or have been sold:<br></p>



<pre class="wp-block-preformatted">&lt;div class="item dogs sale"&gt;Item 1&lt;/div&gt;<br>&lt;div class="item cats sale"&gt;Item 2&lt;/div&gt;<br>&lt;div class="item fish sale"&gt;Item 3&lt;/div&gt;<br>&lt;div class="item fish sold"&gt;Item 4&lt;/div&gt;<br></pre>



<p>And we want to see all the fish that are for sale:<br></p>



<pre class="wp-block-preformatted">const saleItems = document.getElementsByClassName('item fish sale');<br>//Output: &lt;div class="item fish sale"&gt;Item 3&lt;/div&gt;</pre>



<p>That’s pretty useful, right?<br></p>



<p><a href="https://codepen.io/TheWebDeveloperGuide/pen/jRPwvX?editors=1010" target="_blank" rel="noopener">You can check out the Codepen I used for this demonstration here</a>; fork it and have a play around!<br></p>



<p>Now, let’s take a look at the <strong><em>querySelectorAll</em></strong> Javascript method and see how we can use this to achieve the same results.</p>



<h2 class="wp-block-heading">Using querySelectorAll</h2>



<p>Another way you can use Javascript to get an element by a class is to use the <strong><em>querySelectorAll</em></strong> Javascript method.</p>



<p>The difference between the <strong><em>getElementsByClassName</em></strong> and <strong><em>querySelectorAll </em></strong>Javascript methods isn’t that much when it comes to getting elements by a class name. <br></p>



<p>Overall, however, the <strong><em>querySelectorAll</em></strong> method is more powerful and allows you to grab pretty much any element by pretty much any means imaginable.<br></p>



<p>What I mean by that is you can use this method to select an element by class, id, element type, data attribute or a combination of those elements. <br></p>



<p>Let’s take a look at the the <strong><em>querySelectorAll</em></strong> Javascript method in action.<br></p>



<p>First, let’s define our elements:<br></p>



<pre class="wp-block-preformatted">&lt;div class="items"&gt;<br>&lt;div id="1" data-type="fish" data-status="sale" class="item"&gt;Fish 1 for Sale&lt;/div&gt;<br>&lt;div id="2" data-type="doggo" data-status="sale" class="item"&gt;Doggo 1 for Sale&lt;/div&gt;<br>&lt;div id="3" data-type="doggo" data-status="sold" class="item"&gt;Doggo 2 sold&lt;/div&gt;<br>&lt;div id="4" data-type="fish" data-status="sale" class="item"&gt;Fish 2 for Sale&lt;/div&gt;<br>&lt;/div&gt;<br></pre>



<p>You’ll notice this time I’ve been a little creative with my elements, adding both IDs and data attributes to them.<br></p>



<p>Now, let’s take a look at some of our queries in action. First, we’re going to use <strong><em>querySelectorAll</em></strong> to get all the elements with the item class.<br></p>



<pre class="wp-block-preformatted">let items = document.querySelectorAll('.item');<br>//Output <br>NodeList(4): <br>div#1.item: <br>div#2.item: <br>div#3.item: <br>div#4.item<br>length: 4__proto__: NodeList<br></pre>



<p>This will return all 4 divs with the item class.<br></p>



<p>Interestingly, we’d get pretty much the same result with any of the following <strong><em>querySelectorAll </em></strong>queries:<br></p>



<pre class="wp-block-preformatted">let items = document.querySelectorAll('[data-type=”fish]');<br>let items = document.querySelectorAll('div.item'); <br>let items = document.querySelectorAll('[data-status]');<br>let items = document.querySelectorAll('#1, #2, #3, #4, #5');<br></pre>



<p>There are a couple of things to note in the examples above.</p>



<h3 class="wp-block-heading">The div.Item</h3>



<p>The first is that we had to use div.item there. If we used just div, the parent element would’ve been included too, as it’s also a div.</p>



<h3 class="wp-block-heading">Accessing Data Attributes</h3>



<p>The second is the way in which you call data attributes with <strong><em>querySelectorAll</em></strong>. Data attributes are to be wrapped in square brackets and can be called just based on the data attribute itself or the data attribute and its value. <br></p>



<p>As you can see from the example above, I’ve used both methods. The first is to get all of the elements that have a data-type of “fish” and the second is to get me all elements with the status data attribute.</p>



<p>I go into a little more detail about access Data Attributes in my <a href="https://www.thewebdeveloperguide.com/javascript-get-data-attribute/">Javascript Get Data Attribute article &#8211; it&#8217;s well worth a read if you&#8217;re interested</a>.</p>



<h3 class="wp-block-heading">Accessing IDs</h3>



<p>IDs have to be accessed by naming them all like in the example above. There is no way to just select every element that has an ID and other methods, such as data attributes or classes are a better way of getting access to a collection of elements in this manner.</p>



<h2 class="wp-block-heading">Javascript Get Element By Class: Conclusion</h2>



<p>If you want to access a group of elements in Javascript by class, then using the <strong><em>getElementsByClassName</em></strong> or <strong><em>querySelectorAll</em></strong> methods are your two best options. Both return the same results, BUT the <strong><em>getElementsByClassName</em></strong> method <g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Grammar multiReplace" id="6" data-gr-id="6">is</g> faster <a href="http://jsben.ch/4KKjp" target="_blank" rel="noopener"><g class="gr_ gr_5 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Grammar only-ins replaceWithoutSep" id="5" data-gr-id="5">according</g> our performance tests</a>. &nbsp;<br></p>



<p>However, if your goal is to get just one element then the <strong><em>getElementsByClassName </em></strong>is probably not your best option. Getting the element by its ID or data attribute is, depending what attributes the element holds. </p>



<h2 class="wp-block-heading">Further Reading:</h2>



<ul>
<li><a href="https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp" target="_blank" data-type="URL" data-id="https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp" rel="noreferrer noopener">W3Schools</a></li>



<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName" target="_blank" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName" rel="noreferrer noopener">Mozilla Get Elements By Class Name</a></li>



<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll" target="_blank" rel="noreferrer noopener">Mozilla Query Selector All</a></li>
</ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>CSS Z-Index Not Working! Send Help!</title>
		<link>https://thewebdeveloperguide.com/css-z-index-not-working-send-help/</link>
		
		<dc:creator><![CDATA[Kris Barton]]></dc:creator>
		<pubDate>Thu, 28 Mar 2019 15:26:25 +0000</pubDate>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Frontend]]></category>
		<category><![CDATA[Quick Tips]]></category>
		<category><![CDATA[css positioning]]></category>
		<category><![CDATA[css z-index not working]]></category>
		<category><![CDATA[positioning]]></category>
		<category><![CDATA[z-index]]></category>
		<guid isPermaLink="false">https://www.thewebdeveloperguide.com/?p=106</guid>

					<description><![CDATA[You're CSS z-index isn't working? Here's why:]]></description>
										<content:encoded><![CDATA[
<p>“Help!! CSS z-index not working!!! WTF!!!!”<br></p>



<p>Is this you (but without the cursing)? Don’t worry &#8211; I feel your pain. No matter how many pop-ups or fixed navigation systems I make, I always seem to forget the golden rule with the CSS z-index selector: <em>they only work on specifically positioned elements</em>.</p>



<p>Gets me <em>every single time.</em></p>



<p><strong>TL;DR:</strong> the most common cause for z-index not working is not explicitly declaring a CSS position value (i.e. position: relative, absolute, fixed or stick) on the element.<br></p>



<p>But if this hasn’t solved your z-index issue or just want to get a little more information about the CSS property, then let’s go a little deeper.</p>



<h2 class="wp-block-heading">What&#8217;s a CSS z-i<g class="gr_ gr_7 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="7" data-gr-id="7">ndex</g>?</h2>



<p>I think the W3Schools definition of the z-index property sums it up the best:<br></p>



<blockquote class="wp-block-quote">
<p><em>“The z-index property specifies the stack order of an element.”</em><br></p>
<cite>W3Schools &#8211; <br><a href="https://www.w3schools.com/cssref/pr_pos_z-index.asp" target="_blank" rel="noopener">https://www.w3schools.com/cssref/pr_pos_z-index.asp</a> </cite></blockquote>



<p>This basically means you can use this CSS property to stack items on top of each other. <br></p>



<p>Another good way I like to look at it is: it&#8217;s basically the concept of layers for websites. </p>



<p>If you’ve ever used any kind of decent image editing/creation software like Photoshop, GIMP or maybe even Canva, then will no doubt have come across the concept of layers: the ability place images, shapes, text and anything else you might use on top of each other to create a stunning effect or display.<br></p>



<p>That’s what the CSS z-index property can do for your website design.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" loading="lazy" width="400" height="400" src="https://www.thewebdeveloperguide.com/wp-content/uploads/2019/03/tried-z-index-1-liked-it.jpg" alt="Tried z-index: 1; Liked it sudden realisation meme. CSS z-index is not working article." class="wp-image-108" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2019/03/tried-z-index-1-liked-it.jpg 400w, https://thewebdeveloperguide.com/wp-content/uploads/2019/03/tried-z-index-1-liked-it-150x150.jpg 150w, https://thewebdeveloperguide.com/wp-content/uploads/2019/03/tried-z-index-1-liked-it-300x300.jpg 300w" sizes="(max-width: 400px) 100vw, 400px" /></figure></div>


<h2 class="wp-block-heading">I&#8217;ve set the positioning, but my CSS z-index is not working!</h2>



<p>Okay, you&#8217;ve read the section above and have a pretty good grip on the concept of the z-index property. You&#8217;ve also set a CSS position value on the element, but your CSS z-index is still not working. </p>



<p>What now?</p>



<p>Well, the next thing to investigate is the order of your HTML elements and how you&#8217;ve applied your z-index property to them.</p>



<p>Here&#8217;s a pretty good example how the CSS z-index works in a real-world scenario that might just fix your problem.</p>



<h2 class="wp-block-heading">How does the CSS z-index Property Work?</h2>



<p>The CSS z-index property works by assigning the property with a numeric value to any element. <br></p>



<p>The property can take large numeric values, as well as minus values should you want to position elements further back in the stack.<br></p>



<p>An element without a z-index specifically assigned to it, automatically inherits in the z-index of its parent and if the parent element doesn’t have a value set, then the default z-index is 0.<br></p>



<p>Here’s a visual demonstration of how it works:<br></p>



<pre class="wp-block-preformatted"><p class="codepen" data-height="265" data-theme-id="0" data-default-tab="css,result" data-user="TheWebDeveloperGuide" data-slug-hash="YgbKdR" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;" data-pen-title="Help! My z-index isn't working! The Web Developer Guide">
  <span>See the Pen <a href="https://codepen.io/TheWebDeveloperGuide/pen/YgbKdR/" target="_blank" rel="noopener">
  Help! My z-index isn't working! The Web Developer Guide</a> by Kris Barton (<a href="https://codepen.io/TheWebDeveloperGuide" target="_blank" rel="noopener">@TheWebDeveloperGuide</a>)
  on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</span>
</p>
<script async="" src="https://static.codepen.io/assets/embed/ei.js"></script>
</pre>



<p>As you can see from the example above, we’re trying to position both layer 1 and layer 2 to the top left of the base layer. To do this we’re using the absolute positioning CSS property along with the z-index property.<br></p>



<p>As you can see, the orange layer (layer 2) is the layer on top. This is because we’ve set the z-index for the layer to 2. The blue layer (layer 1) is set to a z-index of 1, so layer 2 will be displayed on top.<br></p>



<p>But what if we set layer 2 to have a z-index of 1? You might think that layer 1 would take precedence and layer 2 would be hidden behind it, but that’s not what happens.<br></p>



<p>Because layer 2 uses absolute positioning and its HTML element is underneath layer 1, it takes precedence. This can be tested by moving layer 1’s element underneath layer 2.<br></p>



<p>Now, if we alter the layer 2 z-index to have a value of 2 rather than 1, layer 2 takes precedence again because we’ve explicitly stated it should be place higher than layer 1 in the CSS.<br></p>



<p>Very interesting stuff (at least, it is for geek like me).</p>



<h2 class="wp-block-heading">What can you do with a z-index?</h2>



<p>Okay, so there’s the basic functionality of the z-index CSS property so let’s take a look at some real world examples.<br></p>



<p>Let’s say we want to create a fixed navigation menu that hovers over the main page content. Then, whenever an option is clicked a sub menu is displayed over the top of the floating navigation menu and the main content. This is a scenario where the z-index CSS property becomes essential.<br></p>



<p>To do this, we’ll be using HTML5, CSS and Javascript &#8211; <a href="https://codepen.io/TheWebDeveloperGuide/pen/xBNaBZ" target="_blank" rel="noopener">click here to jump to the codepen</a> (a codepen embed can’t do this bad boy justice).<br></p>



<h3 class="wp-block-heading">Z-Index: Get Your Layers Right!</h3>



<p>As you can see from the code demo, I’m setting the z-index in 2 places:<br></p>



<ol>
<li>I’m setting the main navigation panel to have a z-index of 1.</li>



<li>I’m setting the sub navigation panels to have a z-index of 2.</li>
</ol>



<p>I want the layering of my elements to be the sub navigation links on the top, then the navigation and finally the content behind them. This could’ve been achieved a little easier than I’ve done it in this example, but I wanted to demonstrate the z-index element hierarchy in action.<br></p>



<p>I’ve included the HTML elements in this order:<br></p>



<ol>
<li>Sub navigation links.</li>



<li>Navigation panel.</li>



<li>Content.</li>
</ol>



<p>Because I’ve added the sub navigation links first, I have to specifically assign them a higher z-index than the navigation panel. This is because if the second element has<strong> the same z-index</strong>, it will take precedence over the first and <strong>will overlap it</strong>. <br></p>



<p>In our example, it would mean the sub navigation links would be hidden behind the navigation panel.<br></p>



<p>Conversely, if I move the sub navigation below the navigation panel and changed its z-index to 1, <strong>then the sub navigation items would still overlap the navigation panel</strong>. <br></p>



<p>Pretty interesting stuff once you break it down and examine it. Feel free to fork my codepen and have a play around with the elements yourself.</p>



<h2 class="wp-block-heading">Top Tip: Think About Your z-index Elements In Advance When Planning Your Website</h2>



<p>When creating a website, you might find yourself with a number of different elements that will need to be layered and overlap on the same page, sometimes at the same time.</p>



<h3 class="wp-block-heading">Start Planning</h3>



<p>It’s worth planning in advance the order in which your z-index elements should take precedence. For example, should your popup box be able to overlap your navigation element? Or should it be the other way around.<br></p>



<p>I say this because a lot of developers will automatically set the z-index of an element to a high number (something like 999) and this okay because it’s definitely going to overlap the page with such a high value, but doesn’t take into account scenarios where you have two or more overlapping elements action and open at the same time.</p>



<p>Let me hammer home that point in meme form:</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" loading="lazy" width="498" height="457" src="https://www.thewebdeveloperguide.com/wp-content/uploads/2019/03/css-z-index-not-working.jpg" alt="Too Damn High Meme about the CSS Z-Index in CSS z-index not working article" class="wp-image-107" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2019/03/css-z-index-not-working.jpg 498w, https://thewebdeveloperguide.com/wp-content/uploads/2019/03/css-z-index-not-working-300x275.jpg 300w" sizes="(max-width: 498px) 100vw, 498px" /></figure></div>


<p>This might not ever be a scenario you need to worry about, but if you think it might be then it’s a good idea to come up with a more sensible z-index valuation system.<br></p>



<p>For example, you can always image the base layer of your website to have a z-index value of 0. Set the next value you’d like to overlap to have a z-index value of 1. If then you decide you need another element to overlap and it’s more important to the user to display it over the top of the previous overlapping element, then set it to 2 and so on.<br></p>



<p>This way, you can always guaranteed the right overlay will be displayed to the user. </p>



<h2 class="wp-block-heading">Further Reading:</h2>



<ul>
<li><a href="https://www.w3schools.com/cssref/pr_pos_z-index.asp" target="_blank" rel="noopener">https://www.w3schools.com/cssref/pr_pos_z-index.asp</a></li>



<li><a href="https://css-tricks.com/almanac/properties/z/z-index/" target="_blank" rel="noopener">https://css-tricks.com/almanac/properties/z/z-index/</a></li>



<li><a href="https://philipwalton.com/articles/what-no-one-told-you-about-z-index/" target="_blank" rel="noopener">https://philipwalton.com/articles/what-no-one-told-you-about-z-index/</a></li>



<li><a href="https://webdesign.tutsplus.com/articles/what-you-may-not-know-about-the-z-index-property--webdesign-16892" target="_blank" rel="noopener">https://webdesign.tutsplus.com/articles/what-you-may-not-know-about-the-z-index-property&#8211;webdesign-16892</a></li>
</ul>



<p><br></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Javascript Remove From Array</title>
		<link>https://thewebdeveloperguide.com/javascript-remove-from-array/</link>
		
		<dc:creator><![CDATA[Kris Barton]]></dc:creator>
		<pubDate>Mon, 25 Mar 2019 09:28:38 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Frontend]]></category>
		<category><![CDATA[Quick Tips]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[javascript arrays]]></category>
		<category><![CDATA[remove from javascript arrays]]></category>
		<guid isPermaLink="false">https://www.thewebdeveloperguide.com/?p=100</guid>

					<description><![CDATA[Want to remove data from an array using JS? Here's how:]]></description>
										<content:encoded><![CDATA[
<p>You want to use Javascript to remove a value from an array, but you can’t quite remember how. You think the answer should be something obvious and simple, yet you can’t quite put your finger on what it actually is. <br></p>



<p><em>Perhaps array.remove() is a thing? </em>You think, hopefully. <em>That would be REALLY useful.</em>.<br></p>



<p>Guess what. It’s not a thing and that, quite understandably, frustrates you. <br></p>



<p>You think, <em>Well, what the hell should I do then?</em> <br></p>



<p>Let’s take a look at your options.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" loading="lazy" width="500" height="701" src="https://www.thewebdeveloperguide.com/wp-content/uploads/2019/03/2wvm8s.jpg" alt="Javascript Remove from Array | How to remove items from an array using Javascript" class="wp-image-101" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2019/03/2wvm8s.jpg 500w, https://thewebdeveloperguide.com/wp-content/uploads/2019/03/2wvm8s-214x300.jpg 214w" sizes="(max-width: 500px) 100vw, 500px" /></figure></div>


<h2 class="wp-block-heading">Javascript Remove First Item from Array with the Shift Method</h2>



<p>Before we get into some of the more complex methods of removing items from an array, it’s probably a good idea to start with the basics &#8211; removing the first item of an array.<br></p>



<p>This can be achieved quite easily with the Javascript <strong>Shift</strong> method. Let’s take a look at an example:<br></p>



<pre class="wp-block-preformatted">Let items = [‘item1’, ‘item2’, ‘item3’];<br>items.shift(); // will get you [‘item2’, ‘item3’]<br></pre>



<p>And to add an item to the start of the array, you use the unshift Javascript method. Let’s take a look at that in action:</p>



<pre class="wp-block-preformatted">Let items = [‘item2’, ‘item3’];<br>items.unshift(‘item1’); // will get you [‘item1’, ‘item2’, ‘item3’]<br></pre>



<p>Pretty straightforward stuff, right? Now let’s take a look at removing the last item from an array.</p>



<h2 class="wp-block-heading">Javascript Remove Last Item from Array with the Pop Method</h2>



<p>As you might have already guessed, this Javascript method is just as straightforward as the shift method. <br></p>



<p>It’s called <strong>pop</strong> and it works in the exact same way as shift. Let’s take a look:<br></p>



<pre class="wp-block-preformatted">Let items = [‘item1’, ‘item2’, ‘item3’];<br>items.pop(); // will get you [‘item1’, ‘item2’]<br></pre>



<p>To add an item back to the end of the array, you use the push method, like this:</p>



<pre class="wp-block-preformatted">Let items = [‘item1’, ‘item2’];<br>items.push(‘item3’); // will get you [‘item1’, ‘item2’, ‘item3’]<br></pre>



<p>But removing an item from anywhere within the array? That’s where things get a little bit more complex.</p>



<h2 class="wp-block-heading">Javascript Remove from Array with Splice Method</h2>



<p>We’ll start with the most common method for removing an item from an array: <strong>splice</strong>.<br></p>



<p>What is the Javascript splice method? The MDN Web Docs definition is:<br></p>



<p><em>The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.</em><br></p>



<p>You basically use the splice to determine three things:<br></p>



<ol>
<li>Which part of the array you want to change &#8211; it’s index.</li>



<li>How many items in the array you want to remove.</li>



<li>The new item you want to insert into the array.</li>
</ol>



<p>So the syntax for the splice method is like this:<br></p>



<pre class="wp-block-preformatted">array.splice(index, howmany, replacement items);<br></pre>



<p>So let’s take a look at a standard splice method in action. The scenario is, we have an array of items and we want to replace the second item in the array with a different item.</p>



<pre class="wp-block-preformatted">Let items = [‘item1’, ‘item2’, ‘item3’];<br> <br>items.splice(1,1,’item4’); // Will get you [‘item1’, ‘item4’, ‘item3’] <br></pre>



<p>Here, I’m telling the splice method to index 1 and replace 1 item with the ‘item4’ value.<br><br><em>But wait. If you’re starting at index 1, why is it the second item in the array that’s being replaced rather than the first? You might be thinking.</em><br><br>Good question. It’s because the array index actually starts at 0, not 1. So in our array, it would go 0 = ‘item1’, 1 = ‘item2’, 2 = ‘item3’.<br><br>Let’s test this by changing the 1 to a 0 in our splice method.<br></p>



<pre class="wp-block-preformatted">Let items = [‘item1’, ‘item2’, ‘item3’];<br>items.splice(0,1,’item4’); // Will get you [‘item4’, ‘item2’, ‘item3’] </pre>



<h3 class="wp-block-heading">Complex Array Splicing</h3>



<p>We’ve used the Javascript splice method to replace an item in an array, but what if you just wanted to remove an item? What then?<br></p>



<p>Well then you just don’t stipulate the replacement item.</p>



<pre class="wp-block-preformatted">Let items = [‘item1’, ‘item2’, ‘item3’];<br>items.splice(1,1); // Will get you [‘item1’, ‘item3’] <br></pre>



<p>Pretty straightforward so far, right? <em>So why can this be complex?</em><br></p>



<p>What if you wanted to remove an item from an array, but didn’t know the index of the item within the array? It’s a likely scenario, especially when dealing with dynamic content.<br></p>



<p>So how can we accomplish this? We’ll need to do three things:<br></p>



<ol>
<li>We’re going to need to loop through the array.</li>



<li>We’re going to need to check the value we want to remove against all the values in the array.</li>



<li>If we find the value in the array, we need to remove it from the array.</li>
</ol>



<p>Let’s take a look how we can do this:<br></p>



<pre class="wp-block-preformatted">let moreItems = [1, 2, 3, 4, 5];<br>let removeItem = 3;<br><br>for (i = 0; i &lt; moreItems.length; i++) {<br> &nbsp;if(moreItems[i] === removeItem) {<br> &nbsp;&nbsp;&nbsp;moreItems.splice(i,1);<br> &nbsp;}<br>}<br>// will get us [1,2,4,5]<br></pre>



<p>Okay, let’s run through what I’ve done here.<br></p>



<p>First of all, I’ve defined our array and then I’ve defined the item we want to find in our array and remove.<br></p>



<p>Then I’ve run through the array using the Javascript for loop. I’ve created a variable, called it i and set its initial value to 0. Then I’ve told the loop to run through the array until the end of the array, which I’ve dynamically determined using the .length Javascript method. Then I’ve set the loop to increment my i variable by 1 for every loop until it reaches the length of the array.<br></p>



<p>Inside the loop, we’re using our i variable as an index for our variable and then comparing each array value to the value we’re searching for.<br></p>



<p>If we find a match, we use that i variable as our splice index and remove it from our array.<br></p>



<p>Then the loop continues, because you never know when there might be more of those values we want to remove.<br></p>



<p>Let me demonstrate by adding more items to the array.<br></p>



<pre class="wp-block-preformatted">let moreItems = [1, 2, 3, 4, 5, 2, 6, 7, 3, 8, 9, 6];<br>let removeItem = 3;<br><br>for (i = 0; i &lt; moreItems.length; i++) {<br> &nbsp;if(moreItems[i] === removeItem) {<br> &nbsp;&nbsp;&nbsp;moreItems.splice(i,1);<br> &nbsp;}<br>}<br><br>// will get us: [1,2,4,5,2,6,7,8,9,6]<br></pre>



<p>But our fun with removing items from a array doesn’t end there. There is, in fact, a slightly better way handle item removal with the Javascript filter method.</p>



<h2 class="wp-block-heading">Javascript Remove from Array with Filter Method</h2>



<p>The Javascript filter method accomplishes what our splice method inside a FOR loop did, just with slightly less lines of code and without actually having to use a for loop. The filter method also allows for a little more added cool functionality in case we wanted to be a little clever.<br></p>



<p>First, let’s take a look at how we can use the filter method to remove items from an array.</p>



<pre class="wp-block-preformatted">let moreItems = [1, 2, 3, 4, 5, 2, 6, 7, 3, 8, 9, 6];<br>let removeItem = 3;<br><br>moreItems = moreItems.filter(item =&gt; item !== removeItem);<br>// will get us: [1,2,4,5,2,6,7,8,9,6] <br></pre>



<p>With the Javascript filter method, that’s literally all there is to it.<br></p>



<p>Let’s take a look what’s going on here:<br></p>



<ol>
<li>We’re re-assigning our array to contain the filtered items.</li>



<li>Then the filter method will search through each item in our array and we declare a variable for each item (in the example above, we call it item, but it could be called anything you like) and compares it against the value we want to remove.</li>



<li>If the item is not equal to the item we want to remove, we keep it.</li>
</ol>



<p>One other thing to note about the example about is the use of the Javascript Arrow function (=&gt;). If you’re unfamiliar with it, the Arrow Function isn’t a part of the Javascript Filter method &#8211; it’s actually the new fangled way of writing functions in ES2015 Javascript. Therefore, this piece of code will not work in Internet Explorer at all (but it does work in Edge). For more information on what browsers do currently support this, <a href="https://caniuse.com/#search=Javascript%20arrow%20functions" target="_blank" rel="noopener">check out CanIUse</a>.<br></p>



<p>So, the above ES2015 written code is basically this in old Javascript:</p>



<pre class="wp-block-preformatted"> moreItems = moreItems.filter(function(item){<br> &nbsp;return item !== removeItem;<br>});<br></pre>



<p>Makes sense, right?<br></p>



<p>There are also a few extra cool things you can do with the Javascript method which might appeal to your array item removal needs &#8211; you can set conditions.<br></p>



<p>For example, say we only wanted items in the array that was bigger than 3. We could do this:</p>



<pre class="wp-block-preformatted">var biggerThan = function(value) {<br> &nbsp;return value &gt; 3;<br>}<br><br>moreItems = moreItems.filter(biggerThan);<br>// will get us [4,5,6,7,8,9,6]<br></pre>



<p>Here we create a function that accepts a value and returns the value if it’s bigger than 3. We pass this function into our filter method and the filter method knows to access the <em>biggerThan</em> function with each item in our array and filter out the unwanted values accordingly.<br></p>



<p>Pretty cool, right? </p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>So what’s the best way of removing items from an array?<br></p>



<p>Personally, I prefer using the filter function over the splice function because it’s less code and I think it’s a nicer way to go about things. BUT, if I was ever in a situation where I just wanted to remove the first or last item from my array, I’d use the shift and pop Javascript methods accordingly. <br></p>



<p>I guess my point is, the best way to use Javascript to remove items from an array depends on what exactly you need to do and your situation.<br></p>



<h3 class="wp-block-heading">Further Reading:</h3>



<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill</a></li>



<li><a href="https://www.w3schools.com/jsref/jsref_splice.asp" target="_blank" rel="noopener">https://www.w3schools.com/jsref/jsref_splice.asp</a></li>



<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice</a></li>



<li><a href="https://alligator.io/js/push-pop-shift-unshift-array-methods/" target="_blank" rel="noopener">https://alligator.io/js/push-pop-shift-unshift-array-methods/</a></li>



<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter</a></li>



<li><a href="https://www.w3schools.com/jsref/jsref_filter.asp" target="_blank" rel="noopener">https://www.w3schools.com/jsref/jsref_filter.asp</a></li>



<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions</a></li>
</ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Vertically Align Text Using CSS</title>
		<link>https://thewebdeveloperguide.com/css-vertical-align-text/</link>
		
		<dc:creator><![CDATA[Kris Barton]]></dc:creator>
		<pubDate>Mon, 04 Mar 2019 13:01:17 +0000</pubDate>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Frontend]]></category>
		<category><![CDATA[Quick Tips]]></category>
		<guid isPermaLink="false">https://www.thewebdeveloperguide.com/?p=6</guid>

					<description><![CDATA[Want to know how to vertically align text in CSS? Here's how:]]></description>
										<content:encoded><![CDATA[
<p>You have a large HTML Div with some text inside. You’ve got text centered horizontally with CSS no problem, but vertically? Hmm. That’s a little trickier and you’re stumped.<a href="https://shareasale.com/r.cfm?b=1291521&amp;u=508016&amp;m=41388&amp;urllink=&amp;afftrack=" target="_blank" rel="noreferrer noopener"></a></p>



<p>Or maybe you want a completely different kind of CSS vertical align text altogether. Maybe you have a line of text with two different font sizes and you want the smaller font to be vertically aligned to the middle of the larger font size &#8211; like a quote or citation or something like that. <a rel="noreferrer noopener" target="_blank" href="https://shareasale.com/r.cfm?b=1291521&amp;u=508016&amp;m=41388&amp;urllink=&amp;afftrack="></a></p>



<p>Both are completely different scenarios, with different solutions but both of them make you want to scream the same thing: CSS <g class="gr_ gr_3 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="3" data-gr-id="3">vertical align</g> text how I do dis???</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" loading="lazy" width="500" height="500" src="https://www.thewebdeveloperguide.com/wp-content/uploads/2019/03/how_i_do_dis.jpg" alt="CSS Vertical Align Text - How I Do Did - The Web Developer Guide" class="wp-image-21" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2019/03/how_i_do_dis.jpg 500w, https://thewebdeveloperguide.com/wp-content/uploads/2019/03/how_i_do_dis-150x150.jpg 150w, https://thewebdeveloperguide.com/wp-content/uploads/2019/03/how_i_do_dis-300x300.jpg 300w" sizes="(max-width: 500px) 100vw, 500px" /></figure></div>


<p>It can be frustrating, but we have options &#8211; let’s take a look. <br></p>



<h2 class="wp-block-heading">Defining our Scenarios</h2>



<p>I know we kinda defined the scenarios already in the introduction to this post, but let’s make sure we’re absolutely clear on what we’re trying to accomplish here.</p>



<h3 class="wp-block-heading">Scenario 1</h3>



<p>We have an HTML div where we want the text inside the div to be vertically aligned at the center. Like this:<br></p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" loading="lazy" width="576" height="305" src="https://www.thewebdeveloperguide.com/wp-content/uploads/2019/03/scenario_1.png" alt="CSS Vertical Guide - Scenario 2 - The Web Developer Guide" class="wp-image-15" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2019/03/scenario_1.png 576w, https://thewebdeveloperguide.com/wp-content/uploads/2019/03/scenario_1-300x159.png 300w" sizes="(max-width: 576px) 100vw, 576px" /></figure></div>


<h3 class="wp-block-heading">Scenario 2</h3>



<p>We have a line code that has two different font sizes. We want the smaller font size to be vertically aligned to the middle of the larger font size. Like this:<br></p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" loading="lazy" width="481" height="63" src="https://www.thewebdeveloperguide.com/wp-content/uploads/2019/03/scenario_2.png" alt="CSS Vertical Align Text - Scenario 1 - The web Developer Guide" class="wp-image-16" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2019/03/scenario_2.png 481w, https://thewebdeveloperguide.com/wp-content/uploads/2019/03/scenario_2-300x39.png 300w" sizes="(max-width: 481px) 100vw, 481px" /></figure></div>


<p>Let’s start off with the first scenario.</p>



<h2 class="wp-block-heading">CSS Vertical Align Text with CSS Flexbox</h2>



<p>So we want to vertically align text in a div or some other container. <br></p>



<p>One way to do this, is to use CSS Flexbox. If you’re unfamiliar with Flexbox, it’s a CSS layout module that makes it easier to make your layout design more flexible and responsive.<br></p>



<p>Flexbox allows you to have a little more control over your layout and makes vertically aligning text a breeze using the align-items selector. <br></p>



<p>Let’s take a look at the code:<br></p>



<p><p class="codepen" data-height="500" data-theme-id="dark" data-default-tab="css,result" data-user="TheWebDeveloperGuide" data-slug-hash="XGmYab" style="height: 500px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;" data-pen-title="CSS Vertical Align Text Scenario 1 - Flex">
  <span>See the Pen <a href="https://codepen.io/TheWebDeveloperGuide/pen/XGmYab/" target="_blank" rel="noopener">
  CSS Vertical Align Text Scenario 1 &#8211; Flex</a> by Kris Barton (<a href="https://codepen.io/TheWebDeveloperGuide" target="_blank" rel="noopener">@TheWebDeveloperGuide</a>)
  on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</span>
</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script></p>



<p>Here, I’m using 3 CSS Flexbox selectors:<br></p>



<ol>
<li>I’m declaring it a Flexbox item using <em>display: flex; </em>This means that I’m making it possible for anything inside that div (child elements) to be controlled by CSS Flexbox.</li>



<li>I’m using <em>justify-content: center</em> to center the text horizontally.</li>



<li>I’m using <em>align-items: center</em> to align the text vertically.</li>
</ol>



<h3 class="wp-block-heading">Can I Use Flexbox Align-Items?</h3>



<p>Before you take this as your final solution, you should probably first work out whether you’re able to actually use CSS Flex and the align-items selector.<br></p>



<p><em>Why can’t I use it?</em> You might be asking yourself. The answer is simple: browser support. CSS Flex doesn’t work all that great in older browser &#8211; particularly IE (surprise, surprise).<br></p>



<p>In fact, even IE11 is listed as having only partial support (IE Edge supports it completely).<br></p>



<p>So if you need to support older browsers for any reason, just be aware of this. You can find out more about the browser support for the align-items CSS selector <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">at CanIUse.com</a>.</p>



<h2 class="wp-block-heading">CSS Vertical Align Text with CSS Grid</h2>



<p>We can accomplish CSS vertical align text with a newer CSS layout module know as Grid. CSS Grid is a bit of an update on CSS Flexbox and is <em>really </em>useful for making great layouts.<br></p>



<p>Here’s a Codepen showing how we vertically aligned our text using CSS Grid:<br><br><p class="codepen" data-height="500" data-theme-id="dark" data-default-tab="css,result" data-user="TheWebDeveloperGuide" data-slug-hash="MxaZLz" style="height: 500px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;" data-pen-title="CSS Vertical Align Text Scenario 1 - Grid">
  <span>See the Pen <a href="https://codepen.io/TheWebDeveloperGuide/pen/MxaZLz/" target="_blank" rel="noopener">
  CSS Vertical Align Text Scenario 1 &#8211; Grid</a> by Kris Barton (<a href="https://codepen.io/TheWebDeveloperGuide" target="_blank" rel="noopener">@TheWebDeveloperGuide</a>)
  on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</span>
</p>
</p>



<p>For a simple example such as this, it might seem there’s no difference between the CSS Flexbox and CSS Grid layout modules, but once your layout become a little more complicated the power of the Grid layout style will become more and more apparent.</p>



<h3 class="wp-block-heading">Can I Use CSS Grid Align-Items?</h3>



<p>Again, a word of warning before you implement this solution: make sure you’re able to use it on whichever web browsers you support.<br></p>



<p>Despite CSS Grid is a newer technology than CSS Flexbox, there’s still pretty much the same support there. There’s minor support on IE10 and IE11 (limited functionality and what you can do must be limited to IE specific CSS selectors), but every other modern browser is basically fine. <br></p>



<p>Again, you can check out <a href="https://caniuse.com/#search=grid" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">browser support for CSS Grid yourself at CanIUse.com</a>.</p>



<h2 class="wp-block-heading">CSS Vertical Align Text with CSS Absolute Positioning</h2>



<p>With all the wonderful layout functionality that’s built into CSS, using Absolute Positioning in CSS to accomplish our goal of vertically aligning text, in my opinion, is a little bit overkill. <br></p>



<p>BUT for thoroughness, it’s worth mentioning this way of aligning text vertically just in case it’s the only option available to you (for whatever reason).<br></p>



<p>Take a look at our Pen:<br></p>



<p><p class="codepen" data-height="500" data-theme-id="dark" data-default-tab="css,result" data-user="TheWebDeveloperGuide" data-slug-hash="eXJMdz" style="height: 500px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;" data-pen-title="CSS Vertical Align Text Scenario 1 - Absolute Positioning">
  <span>See the Pen <a href="https://codepen.io/TheWebDeveloperGuide/pen/eXJMdz/" target="_blank" rel="noopener">
  CSS Vertical Align Text Scenario 1 &#8211; Absolute Positioning</a> by Kris Barton (<a href="https://codepen.io/TheWebDeveloperGuide" target="_blank" rel="noopener">@TheWebDeveloperGuide</a>)
  on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</span>
</p><br></p>



<p>As you may notice, there’s a little more going on in here. <br></p>



<p>Firstly, if you’ve used absolute positioning in CSS before then you’ll know that if I want my item to be positioned absolutely within the containing div, then that divs positioning must be set explicitly to relative. Otherwise, the div assigned absolute positioning will not be contained to the container &#8211; just the webpage itself. <br></p>



<p>Secondly, you may be wondering about the use of the CSS Calc function. For those of you who haven’t used the Calc function before, your missing out on a really powerful CSS feature. I’m not going to go into too much detail about the function here, but <a href="https://www.w3schools.com/cssref/func_calc.asp" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">go read more about it at W3Schools for more information</a> &#8211; it’ll be SO worth your time. Essentially, what I’m doing here is calculating the true middle of the container div, based on the height of the inner div.<br></p>



<p>Let me explain: when you use top &nbsp;50%, the web browser will calculate 50% from the top of the container div (in this case .box) to the <strong>top</strong> of our inner div (.box__content). This means the content inside the inner div will fall below the middle of the contain div and just look <em>off</em>. <br></p>



<p>There are a number of ways to combat this, but assigning the inner div a set height and using the CSS Calc function to work out absolute center is the sleekest option for me.<br></p>



<p>You could just tweak the top value until it looks right, but then you’ll end up with a value of 47% or some other random number (or magic number if you like) which isn’t as web developer friendly for my liking. <br></p>



<p>Let’s take a look how we can vertically align our text for the second scenario.</p>



<h2 class="wp-block-heading">CSS Vertical Align Text with Vertical Align CSS Selector</h2>



<p>Let’s start off by defining a real-world example of why you might need to vertically align different sized font on the same line.<br></p>



<p>We want to create a standard quote styling in which the actual quote text is larger than the citation. <br></p>



<p>In this situation you’d use the vertical-align selector tag and set it’s value to <em>middle</em>.<br></p>



<p>As the name of the CSS selector suggests, the vertical-align property sets the vertical alignment of an inline or table property. It has a number of cool options:<br></p>



<ol>
<li>Baseline</li>



<li>Top</li>



<li>Middle</li>



<li>Bottom</li>



<li>Sub</li>



<li>Text-Top</li>



<li>Length (in which you can specify a value for the vertical alignment)</li>



<li>Percentage (in which you can specify the percentage of the vertical alignment)</li>
</ol>



<p>For the task we’re trying to accomplish here, we’re going to use the <em>middle </em>option. See our demo Codepen below:<br></p>



<p><p class="codepen" data-height="500" data-theme-id="dark" data-default-tab="html,result" data-user="TheWebDeveloperGuide" data-slug-hash="NJGwKQ" style="height: 500px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;" data-pen-title="CSS Vertical Align Text Scenario 2">
  <span>See the Pen <a href="https://codepen.io/TheWebDeveloperGuide/pen/NJGwKQ/" target="_blank" rel="noopener">
  CSS Vertical Align Text Scenario 2</a> by Kris Barton (<a href="https://codepen.io/TheWebDeveloperGuide" target="_blank" rel="noopener">@TheWebDeveloperGuide</a>)
  on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</span>
</p></p>



<p>This way of vertical alignment in CSS is actually really quite useful, especially of you have a combination of text and images you want to line up just right on the same line. </p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>CSS Vertical Align Text can mean 2 different things.<br></p>



<ol>
<li>You want to align text vertically within a container.</li>



<li>You want larger and smaller text or text and images to align vertically inline.</li>
</ol>



<p>For the first scenario there are 3 different ways to do it:<br></p>



<ol>
<li>Using CSS Flexbox.</li>



<li>Using CSS Grid.</li>



<li>Using CSS Absolute position.</li>
</ol>



<p>Option 1 or 2 are the best ways to vertically align text within a container, but don’t have full support in some of the older web browsers.<br></p>



<p>For the second scenario, there’s only really one option that makes any kind of sense: the vertical-align: middle tag. </p>



<h2 class="wp-block-heading">Further Reading</h2>



<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align" target="_blank" rel="noopener">Vertical Align CSS Property &#8211; MDN Web Docs</a></li>



<li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://www.w3schools.com/cssref/pr_pos_vertical-align.asp" target="_blank">W3Schools Vertical Align Property</a></li>



<li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/" target="_blank">Flexbox Cheat Sheet &#8211; CSS Tricks</a></li>



<li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://www.w3schools.com/css/css3_flexbox.asp" target="_blank">W3Schools CSS Flexbox</a></li>



<li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox" target="_blank">Basic Concepts of Flexbox &#8211; MDN Web Docs</a></li>



<li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://www.w3schools.com/cssref/css3_pr_align-items.asp" target="_blank">Align-Items Property &#8211; W3Schools</a></li>



<li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://www.w3schools.com/css/css_positioning.asp" target="_blank">CSS Positioning &#8211; W3Schools</a></li>



<li><a href="https://www.w3schools.com/cssref/func_calc.asp" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">CSS Calc Function &#8211; W3Schools</a></li>
</ul>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
