<?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>Javascript &#8211; The Web Developer Guide</title>
	<atom:link href="https://thewebdeveloperguide.com/category/frontend/javascript/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>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>Javascript Get Data Attribute</title>
		<link>https://thewebdeveloperguide.com/javascript-get-data-attribute/</link>
		
		<dc:creator><![CDATA[Kris Barton]]></dc:creator>
		<pubDate>Tue, 19 Mar 2019 13:06:18 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Frontend]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[data attributes]]></category>
		<category><![CDATA[front-end]]></category>
		<category><![CDATA[get data attribute]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[javascript data attributes]]></category>
		<category><![CDATA[javascript get data attribute]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">https://www.thewebdeveloperguide.com/?p=51</guid>

					<description><![CDATA[Want to how data attributes work in HTML and JS? Here's how:]]></description>
										<content:encoded><![CDATA[
<p>Are you j<g class="gr_ gr_13 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="13" data-gr-id="13">ust</g> looking for the &#8220;how-to&#8221; and nothing else, don&#8217;t worry &#8211; I&#8217;ve been there. <strong>TL;DR:</strong> You can use Javascript to get Data Attribute data using either the dataset or getAttribute properties.</p>



<p>But if you want a bit more information about using Javascript to get Data Attributes, then let&#8217;s get started.</p>



<p>HTML5 Data attributes are a really cool and useful way of storing more information in your HTML code and help extend the front-end functionality of a webpage or mobile app. <br></p>



<p>But how do you use Javascript to get the data attribute?<br></p>



<p>Let&#8217;s take a look. <a rel="noreferrer noopener" target="_blank" href="https://shareasale.com/r.cfm?b=1144518&amp;u=508016&amp;m=41388&amp;urllink=&amp;afftrack="></a></p>


<div class="wp-block-image">
<figure class="aligncenter"><a href="https://shareasale.com/r.cfm?b=1291521&amp;u=508016&amp;m=41388&amp;urllink=&amp;afftrack=" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://static.shareasale.com/image/41388/SPThemePromoWebBanner336x280V3.png" alt="Get attribute WPEngine Offer"/></a></figure></div>


<h2 class="wp-block-heading">What is a Data Attribute? </h2>



<p>Firstly, let&#8217;s define what I mean by Data Attribute to make sure we&#8217;re all on the same page. <br></p>



<p>Data Attributes are custom HTML attributes that can be added to any HTML5 item and allow us to store extra information we can use and manipulate.The data is localised to the web page or application they’re on and therefore can only be manipulated on that web page or application.<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/03/javascript-get-data-attribute.png" alt="Javascript Get Data Attributes - All the Things meme" class="wp-image-77" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2019/03/javascript-get-data-attribute.png 593w, https://thewebdeveloperguide.com/wp-content/uploads/2019/03/javascript-get-data-attribute-300x213.png 300w" sizes="(max-width: 593px) 100vw, 593px" /></figure></div>


<p>So what data can or <em>should </em>be stored using Data Attributes? What is the correct syntax to use? When should Data Attributes be used?<br></p>



<p>Let’s take a look at a couple of Data Attribute pointers / best practices <a href="https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes" target="_blank" rel="noopener">directly from W3C</a> to answer those questions:<br></p>



<ul>
<li>Data tags should begin with the <em>data- </em>prefix and must contain at least one character after the hyphen. For example, <em>data-tag or data-nav</em> etc.</li>



<li>Custom Data Attributes should only really be used to store custom data and are not intended to replace existing HTML attributes and elements.</li>



<li>Data Attributes will work on any HTML element.</li>



<li>Each HTML element can have any number of Data Attribute properties.</li>



<li>Data Attributes can have any value.</li>
</ul>



<h3 class="wp-block-heading">A Real-World Example of Data <g class="gr_ gr_13 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="13" data-gr-id="13">Attrbutes</g></h3>



<p>Let’s take a look at a real-world example of the HTML5 Data Attribute syntax and what you might use it for:</p>



<pre class="wp-block-preformatted code">&lt;a id='link-1' <br>   data-link='1' <br>   data-target='1' <br>   data-product-title='Worship Coffee T-Shirt' <br>   data-product-img='product.jpg' <br>   data-product-link='https://www.thewebdeveloperguide.com' <br>   class="link'&gt;<br>Worship Coffee Tee&lt;/a&gt;</pre>



<p>In the example above, we have a regular HTML anchor tag. It has a standard HTML ID and Class, but as you can see it has a number of HTML5 Data Attributes too. </p>



<p>Some of these Data Attributes are out of context and are meaningless at this point, but others are a little more obvious. </p>



<p>In our real-world example we&#8217;re going to be making a simple item picker using these HTML5 Data Attributes and Javascript. We&#8217;re going to create links and a content area and the idea is we&#8217;re going to use the data we store in the above anchor tag&#8217;s Data Attributes to build our display.</p>



<p>Let&#8217;s take a look at the Data Attributes in a little more detail: </p>



<ul>
<li>A data-link attribute to help us identify the link from the others (we&#8217;ll be adding more links later).</li>



<li>A data-target attribute, which we&#8217;re going to use to work out where we&#8217;re going to build our display.</li>



<li>A data-product-title attribute, which is going to contain the name of our product.</li>



<li>A data-product-<g class="gr_ gr_400 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="400" data-gr-id="400">img</g> attribute which is going to contain the location of the image we want to display.</li>



<li>A data-product-link attribute which is going to contain a link to where the user can buy the product.</li>
</ul>



<p>Now we&#8217;ve stored our data using Data Attributes, let&#8217;s take a look at how to access and use it.</p>



<h2 class="wp-block-heading">How Can I Use Javascript to Get a Data Attribute?</h2>



<p>There are a couple of different ways to use Javascript to get a Data Attribute:<br></p>



<ol>
<li>Using the .dataset property.</li>



<li>Using the .getAttribute property. &nbsp;</li>
</ol>



<p>Okay, so what’s the difference between the two? The answer is: not much. Obviously, the syntax is a little different for each property but they can be used to basically do the same thing: extract data.<br></p>



<p>The main difference is that the dataset property is solely for accessing custom data in Data Attribute, whereas the getAttribute property is to get data from <strong><em>any attribute</em></strong> within an HTML element.<br></p>



<p>Interestingly, each of the methods <a href="https://jsperf.com/dataset-vs-getattribute-2" target="_blank" rel="noopener">have slightly different performance results</a>. Using the .dataset to get all of the dataset attributes was a little faster than using .getAttribute, HOWEVER, using getAttribute to access a single Data Attribute was actually faster.<br></p>



<p>Also, both properties are pretty much fully supported:<br></p>



<ul>
<li><a href="https://caniuse.com/#search=dataset" target="_blank" rel="noopener">Dataset Browser Support</a>.</li>



<li><a href="https://caniuse.com/#search=getAttribute" target="_blank" rel="noopener">getAttribute Browser Support</a>.</li>
</ul>



<p>In terms of which property is better to use, I think it pretty much comes down to personal preference so let’s take a look at both methods in action.</p>



<h3 class="wp-block-heading">Using Javascript Get to a Data Attribute using Dataset</h3>



<p>The first thing we need to do is to grab the HTML element so we can access it’s properties. There are a couple of ways you can do this using Vanilla Javascript: <br></p>



<ol>
<li>Get the element by its id using the Javascript <strong><em>document.getElementById</em></strong> function.</li>



<li>Or grab the element by a dataset itself using the Javascript <strong>document.querySelector </strong>function.</li>
</ol>



<p>Let’s take a look at that in the code.</p>



<p>First, here&#8217;s a little reminder of the HTML element we want to access. </p>



<pre class="wp-block-preformatted code">&lt;a id='link-1' <br>   data-link='1' <br>   data-target='1' <br>   data-product-title='Example Product' <br>   data-product-img='product.jpg' <br>   data-product-link='https://www.thewebdeveloperguide.com' <br>   class="link'&gt;<br>Worship Coffee Tee&lt;/a&gt;</pre>



<p>Here&#8217;s how we get the element by its ID using the Javascript document.getElementById function:</p>



<pre class="wp-block-preformatted">const link = document.getElementById('link-1');</pre>



<p>And here&#8217;s how we get the same element by a Data Attribute using the Javascript document.querySelector function:</p>



<pre class="wp-block-preformatted">const link = document.querySelector('[data-link="1"]');</pre>



<p>In the above example, I used the data-link Data Attribute as the hook to grab the element in Javascript because that&#8217;s what I intended the function of that Data Attribute to be. However, I could&#8217;ve grabbed the element using any of the Data Attributes in that element with Javascript document.querySelector &#8211; include the class attribute.</p>



<p>Now that we have the HTML element, let&#8217;s access a couple of our Data Attribute&#8217;s using the Javascript Dataset property.</p>



<pre class="wp-block-preformatted">link.dataset.target<br>// This will get us 1<br><br>link.dataset.productTitle<br>// This will get us 'Example Product'<br><br>link.dataset.productImg<br>// This will get us 'product.jpg'</pre>



<p>Did you notice the dataset syntax in both of those examples? The prefix of data- is removed and the attribute name remains. For the second Data Attribute the dash is removed and converted to a camelCase format.<br></p>



<p>This is because the functionality uses <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMStringMap" target="_blank" rel="noopener">DOMStringMap</a> to handle key transformations. </p>



<h3 class="wp-block-heading">Using Javascript to Get a Data Attribute using getAttribute</h3>



<p>Now let’s get our custom data from the Data Attribute using the getAttribute Javascript function.</p>



<p>We still have to get the element using either the <strong><em>document.getElementById</em></strong> or <strong><em>document.querySelector</em></strong> functions like before, but we access the data like this: </p>



<pre class="wp-block-preformatted">const link = document.getElementById('link-1');</pre>



<p>Or like this:</p>



<pre class="wp-block-preformatted">const link = document.querySelector('[data-link="1"]');</pre>



<p>So now we get the Data Attributes by:</p>



<pre class="wp-block-preformatted">link.getAttribute('data-target');<br>// This will get us 1<br> <br>link.getAttribute('data-product-title');<br>// This will get us 'Example Product'<br><br>link.getAttribute('data-product-img');<br>// This will get us 'product.jpg' </pre>



<p>Again, you&#8217;ll notice the syntax used to grab the Data Attribute is completely different from using  the dataset function. When using the getAttribute function, you have to use the full Data Attribute term to access its content.</p>



<p>This is because the getAttribute function is able to access all the attributes in the element (like the class element for example), not just Data Attributes.</p>



<h3 class="wp-block-heading">Bonus: Access Data Attributes using CSS</h3>



<p>While we’re on the subject of Data Attributes, it’s also worth mentioning that you can access and style them directly using CSS. Here’s a really basic example: </p>



<p><p class="codepen" data-height="265" data-theme-id="dark" data-default-tab="html,result" data-user="TheWebDeveloperGuide" data-slug-hash="zbagyO" 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="Styling Data Attributes Directly">
  <span>See the Pen <a href="https://codepen.io/TheWebDeveloperGuide/pen/zbagyO/" target="_blank" rel="noopener">
  Styling Data Attributes Directly</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>Okay, so this functionality may have limited use in real-world coding but it&#8217;s certainly a cool little bit of functionality worth knowing.</p>



<h2 class="wp-block-heading">Using Javascript to get Data Attributes: A Real-World Example</h2>



<p>Before I finish this article, it&#8217;s worth exploring how a web developer may want to use Data Attributes in a real-world example.</p>



<p>Here&#8217;s the scenario: we want a simple HTML/CSS/Javascript item picker (or maybe tab) component to allow users to choose from a series of cool t-shirt designs.</p>



<p>We load all of the relevant data on page load and store it all in Data Attributes within the component&#8217;s relevant HTML elements.</p>



<p>We&#8217;ll be storing:</p>



<ul>
<li>The product title.</li>



<li>The product image URL.</li>



<li>The product link.</li>
</ul>



<p>For the User Interface, we&#8217;re going to display the product title&#8217;s as clickable links, with <g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="6" data-gr-id="6">a HTML</g> div underneath. </p>



<p>The first product will be displayed on page load and the idea is for the user to click the product links to display the relevant product and information.</p>



<p>Let&#8217;s take a look at the Codepen:</p>



<p class="codepen" data-height="500" data-theme-id="dark" data-default-tab="result" data-user="TheWebDeveloperGuide" data-slug-hash="MxQKXj" 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="HTML5 Data Attributes - Read World Example - dataset">
  <span>See the Pen <a href="https://codepen.io/TheWebDeveloperGuide/pen/MxQKXj/" target="_blank" rel="noopener">
  HTML5 Data Attributes &#8211; Read World Example &#8211; dataset</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>



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



<ul>
<li><a href="https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes" target="_blank" rel="noopener">https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes</a> </li>



<li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes</a></li>



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



<li><a href="https://webdesign.tutsplus.com/tutorials/all-you-need-to-know-about-the-html5-data-attribute--webdesign-9642" target="_blank" rel="noopener">https://webdesign.tutsplus.com/tutorials/all-you-need-to-know-about-the-html5-data-attribute&#8211;webdesign-9642</a> </li>



<li><a href="https://www.sitepoint.com/how-why-use-html5-custom-data-attributes/" target="_blank" rel="noopener">https://www.sitepoint.com/how-why-use-html5-custom-data-attributes/</a> 	</li>



<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset</a></li>



<li><a href="https://www.w3schools.com/jsref/met_element_getattribute.asp" target="_blank" rel="noopener">https://www.w3schools.com/jsref/met_element_getattribute.asp</a> </li>
</ul>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
