<?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>HTML &#8211; The Web Developer Guide</title>
	<atom:link href="https://thewebdeveloperguide.com/category/frontend/html/feed/" rel="self" type="application/rss+xml" />
	<link>https://thewebdeveloperguide.com</link>
	<description>A Developers Guide to Web Develoment</description>
	<lastBuildDate>Wed, 08 Feb 2023 10:29:22 +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>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>
