<?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>Frontend &#8211; The Web Developer Guide</title>
	<atom:link href="https://thewebdeveloperguide.com/category/frontend/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>Getting Started With React</title>
		<link>https://thewebdeveloperguide.com/getting-started-with-react/</link>
		
		<dc:creator><![CDATA[Kris Barton]]></dc:creator>
		<pubDate>Mon, 18 Jan 2021 11:10:06 +0000</pubDate>
				<category><![CDATA[Frontend]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://www.thewebdeveloperguide.com/?p=128</guid>

					<description><![CDATA[Wanna get started in React? This detailed article contains everything you need to know!]]></description>
										<content:encoded><![CDATA[
<p>Are you looking at getting started with React but don&#8217;t know where to start? Don&#8217;t worry &#8211; you&#8217;re in the right place!</p>



<p>Let&#8217;s dive right in.</p>



<p><strong>Disclaimer:</strong> before you read this and want to jump right in, here are a couple of things you should probably know (or at least be familiar with) first:</p>



<ul>
<li><strong>Javascript.</strong> React is a Javascript Library so you&#8217;re gonna need to understand at least the basics. I&#8217;d recommend getting started <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" class="rank-math-link" target="_blank" rel="noopener">at MDN Web Docs</a>.</li>



<li><strong>NodeJS.</strong> For the way I&#8217;m going to set up the example React App in this tutorial, you&#8217;ll need to have <a href="https://nodejs.org/en/" class="rank-math-link" target="_blank" rel="noopener">NodeJs</a> installed on your computer and have at least a basic understanding of <a href="https://www.npmjs.com/" class="rank-math-link" target="_blank" rel="noopener">how NPM works</a>. But don&#8217;t let this over face use &#8211; we&#8217;ll just be using NodeJS and NPM to quickly install everything we need (and more) to get a quick install of React working (more on this later).</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="600" height="400" src="https://www.thewebdeveloperguide.com/wp-content/uploads/2021/01/getting-started-with-react.jpg" alt="Getting started with React: all you need to know to set up and start coding in React. " class="wp-image-199" srcset="https://thewebdeveloperguide.com/wp-content/uploads/2021/01/getting-started-with-react.jpg 600w, https://thewebdeveloperguide.com/wp-content/uploads/2021/01/getting-started-with-react-300x200.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" /></figure></div>


<h2 class="wp-block-heading">What is React?</h2>



<p>React is a really popular web technology right now &#8211; and rightly so.</p>



<p>React is an open-source Javascript library that&#8217;s used for building quick User Interfaces (UI&#8217;s).</p>



<p>React was created by Facebook software engineer Jordan Walke as was first deployed on Facebook news feeds in 2011. Since then it&#8217;s been adopted on many big websites such as Instagram, Paypal, Netflix, and many more.</p>



<h2 class="wp-block-heading">Why Use React?</h2>



<p>One of the reasons why React has become so popular is that there are many advantages to using it:</p>



<ul>
<li>Getting started with React is quick &amp; easy.</li>



<li>It promotes a component-based design &#8211; that means code is written to be re-used and therefore building user interfaces is faster.</li>



<li>Allows developers to logically see the flow of data.</li>



<li>It uses a Virtual Dom which allows for better performance when it comes to user interaction and data updates.</li>



<li>A special mashup of HTML and Javascript called <strong>JSX</strong> makes it easier to write code. It also makes the code easier to read and using JSX prevents XSS attacks, so it also makes the code safer. See more information about this <a href="https://reactjs.org/docs/introducing-jsx.html" class="rank-math-link" target="_blank" rel="noopener">in the React Documentation</a>.</li>



<li>ReactJs.org <a href="https://reactjs.org/docs/getting-started.html" class="rank-math-link" target="_blank" rel="noopener">has great documentation</a> and <a href="https://reactjs.org/tutorial/tutorial.html" class="rank-math-link" target="_blank" rel="noopener">tutorials for you to follow</a> to better understand how everything works.</li>
</ul>



<p>Some of those advantages may not make sense to you right now <strong><em>and that&#8217;s okay</em></strong>.</p>



<p>Just wait until you start using it; then everything will click into place and you&#8217;ll fall in love with it just like I have.</p>



<p>Now that we know what React is and why it&#8217;s a good idea to use it, let&#8217;s actually take a look at getting started with React.</p>



<h2 class="wp-block-heading">Getting Started with React: How to set up React</h2>



<p>There are a few of ways to set up React:</p>



<ul>
<li>Import into your HTML file like any other Javascript library (<strong>note:</strong> you&#8217;ll need a couple of other libraries to get it working though &#8211; more on this later).</li>



<li>Use something called Create-React-App to install a quick start React environment.</li>



<li>Use Webpack (and a few other tools, libraries, etc) to create your own React environment. <strong><em>Don&#8217;t worry about this one for now.</em></strong> It&#8217;s a bit advanced for our purposes in this getting started with React article, we&#8217;ll get into this somewhere down the line.</li>
</ul>



<h3 class="wp-block-heading">Adding React to a Webpage like a Library</h3>



<p>The fastest way to add React to a Webpage is to use the HTML Script tag to load into the page like any other Javascript file.</p>



<p>Here&#8217;s a CodePen with a working example:</p>



<p class="codepen" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-height="500" data-theme-id="light" data-default-tab="html,result" data-user="krisbarton" data-slug-hash="wvzYGog" data-pen-title="Loading React Directly into the Web Browsers">See the Pen <a href="https://codepen.io/krisbarton/pen/wvzYGog" target="_blank" rel="noopener"> Loading React Directly into the Web Browsers</a> by Kris Barton (<a href="https://codepen.io/krisbarton" target="_blank" rel="noopener">@krisbarton</a>) on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</p>
<p><script async="" src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script></p>



<p>There&#8217;s lots to unpack here.</p>



<p>Firstly, we need to load more packages to get it working. These packages are:</p>



<ul>
<li>ReactDom.</li>



<li>Babel.</li>
</ul>



<h4 class="wp-block-heading">What is ReactDOM?</h4>



<p>You don&#8217;t have to worry too much about this and how it works, just that you need it.</p>



<p>But if you want a brief explanation, the ReactJs.org documentation does a pretty good job of explaining it:</p>



<p><strong><em>&#8220;The&nbsp;<code>react-dom</code>&nbsp;package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside of the React model if you need to.&#8221;</em></strong></p>



<p>Essentially, it&#8217;s an efficient way of handling DOM elements of a webpage.</p>



<p>In the example above, we use ReactDOM&#8217;s render method to add a component (more on that later) to our div element (with the id of &#8220;root&#8221;).</p>



<p><strong>TL;DR </strong>&#8211; Don&#8217;t worry about how ReactDOM works, just know that we&#8217;re using it and it&#8217;s pretty useful.</p>



<h4 class="wp-block-heading">What is Babel?</h4>



<p>In a nutshell, Babel is a tool that React uses to compile its code to standard Javascript so that web browsers can understand it.</p>



<h4 class="wp-block-heading">Drawbacks of Setting Up React this Way</h4>



<p>Using React this way is absolutely fine functionality-wise.</p>



<p>But for usability and readability? Not so much. For <em>really</em> small apps you might not come across any issues. For bigger apps, enhancing and updating that code is not going to be pleasant &#8211; it&#8217;s going to get out of control pretty quickly and will basically make your life harder.</p>



<p>So what&#8217;s the <em>&#8220;right&#8221;</em> way to set up React? There is no real <em>&#8220;right&#8221;</em> way but using a build environment makes it a whole lot easier and cleaner.</p>



<p>So how do you use React with a build environment? <strong><em>The quickest way is to use Create-React-App.</em></strong> Here&#8217;s how.</p>



<h3 class="wp-block-heading">What is Create-React-App?</h3>



<p>Create-React-App is basically an &#8220;out of the box&#8221; React build environment. You install this and <strong><em>BAM!</em></strong> you have a pre-made React app that contains dummy content.</p>



<p>This tool was created by the developers at Facebook as way for developers new to React to quickly learn how to use it.</p>



<p>It&#8217;s also great for prototyping &#8211; a quick start React app, full of features and functionality that&#8217;s ready to go.</p>



<p>Essentially, if you&#8217;re just getting started with React you should use <strong><em>Create-React-App</em></strong>.</p>



<h3 class="wp-block-heading">How to set-up Create-React-App?</h3>



<p>Create-React-App is installed on the command line and uses NodeJs and NPM (node package manager &#8211; it&#8217;s built into NodeJs).</p>



<p>So the first step in setting up Create-React-App is making sure you have NodeJS installed or, if you already have NodeJS installed, making sure you have the right <em>version</em> installed. You can check what version you&#8217;re currently using, type <em><strong>node -v</strong></em> into a command line.</p>



<p>You will need to have version 8.10 or higher installed in order to use this create-react-app installer.&nbsp;</p>



<p>If you don&#8217;t already have NodeJs installed on your computer, you can <a href="https://nodejs.org/en/download/" class="rank-math-link" target="_blank" rel="noopener">download NodeJs here</a> and install it like you would any other program.</p>



<p>So, what do you do to actually install <strong><em>create-react-app</em></strong>?</p>



<p>You install create-react-app in a command line. You can use any, but my preference is the terminal in <a href="https://code.visualstudio.com/" class="rank-math-link" target="_blank" rel="noopener">VSCode</a>. It&#8217;s my Code Editor of choice, so it just makes sense.</p>



<p>In your command line, you install create-react-app by typing the following:</p>



<pre class="wp-block-code"><code>npx create-react-app my-app</code></pre>



<p>This goes and gets the create-react-app code and installs in a folder called my-app (if that folder doesn&#8217;t exist, one will be automatically created). And yes, you can change the folder name to whatever you&#8217;d like. </p>



<p>Then type this in the terminal:</p>



<pre class="wp-block-code"><code>cd my-app</code></pre>



<p>All this does is get your terminal into the my-app folder. This is so that we can run the next bit of code, which we&#8217;ve installed in this my-app folder. </p>



<p>Obviously, if you&#8217;ve gone ahead and called your folder something else, change the command above to reflect that. So cd &#8220;whatever your folder is&#8221;.</p>



<p>Finally, we want to get the react app running. </p>



<pre class="wp-block-code"><code>npm start</code></pre>



<p>This triggers a function in the package.json file that initializes the application. Don&#8217;t get bogged down on this bit if you don&#8217;t fully grasp what&#8217;s going on here &#8211; the more you use stuff like this, the more it will fall into place. </p>



<p>All you need to know for now is: <strong><em>it starts the React environment for you to view in a web browser.</em></strong></p>



<p>So, if you go to <a rel="noreferrer noopener" href="http://localhost:3000/" target="_blank">http://localhost:3000/</a> in your web browser of choice, your app will be running and you&#8217;ll see a React welcome page.</p>



<p>Now that our React app is up and running, let&#8217;s take a look at some React coding concepts.</p>



<h2 class="wp-block-heading">Getting Started with React: Coding Concepts</h2>



<p>I know what you want to do. </p>



<p>Now the app is set up, you want to go ahead, pull it apart, and do some coding. I know, because that&#8217;s exactly what I&#8217;d want to do.</p>



<p>But before you do, you should check out some of core coding concepts that come with React &#8211; it&#8217;ll make your life a whole lot easier, trust me.</p>



<p>There are 5 main concepts:</p>



<ol>
<li>JSX.</li>



<li>Elements.</li>



<li>Components.</li>



<li>Props.</li>



<li>State.</li>
</ol>



<p>Let&#8217;s take a look at each of them in a bit more detail.</p>



<h3 class="wp-block-heading">JSX</h3>



<p>One of the first things you&#8217;ll come across when building apps in React is JSX.</p>



<h4 class="wp-block-heading">What is JSX?</h4>



<p>JSX stands for Javascript XML.</p>



<p>It&#8217;s a Javascript syntax expression used mostly in React. It basically allows us to easily write HTML within Javascript.</p>



<p>For a basic example of this:</p>



<pre class="wp-block-code"><code>const hello = &lt;h1&gt;Hello, world!&lt;/h1&gt;;</code></pre>



<p>As you can see, we&#8217;re declaring a variable as we normally would in Javascript, but the syntax after that is not common: it&#8217;s neither a string nor HTML&#8230;</p>



<p>&#8230;it&#8217;s JSX.</p>



<p>JSX isn&#8217;t essential for developing in React, but it does make life a whole lot easier. </p>



<p>For example, without JSX the above code snippet would need to be:</p>



<pre class="wp-block-code"><code>const hello = React.createElement('h1', {}, 'Hello, world!');</code></pre>



<p>I think you&#8217;ll agree, just by looking at it JSX is clearly easier to write.</p>



<h4 class="wp-block-heading">Expressions in JSX</h4>



<p>JSX also allows us to write expressions and embed them in the code.</p>



<p>For example, what if we wanted to add introduction text to that Hello, World! greeting?</p>



<pre class="wp-block-code"><code>const greeting = "My name is Kris Barton.";
const hello = &lt;h1&gt;Hello, World! {greeting}&lt;/h1&gt;

ReactDOM.render(
  hello,
  document.getElementById('root')
);</code></pre>



<p>Let&#8217;s see this in action in CodePen:</p>



<p class="codepen" data-height="500" data-theme-id="light" data-default-tab="html,result" data-user="krisbarton" data-slug-hash="JjRmQmb" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="JSX Expressions">
  <span>See the Pen <a href="https://codepen.io/krisbarton/pen/JjRmQmb" target="_blank" rel="noopener">
  JSX Expressions</a> by Kris Barton (<a href="https://codepen.io/krisbarton" target="_blank" rel="noopener">@krisbarton</a>)
  on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</span>
</p>
<script async="" src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>



<p>With Expressions, you can embed pretty much anything from function output or equations like 2 + 2&#8230;it&#8217;s really cool. </p>



<h4 class="wp-block-heading">JSX Can Used in Logic</h4>



<p>Because JSX is compiled to Javascript, logic may be used to render elements.</p>



<p>What does this mean? We may use <strong>if</strong> and <strong>for</strong> statements to determine output.</p>



<p>For example:</p>



<pre class="wp-block-code"><code>function doGreeting(user) {
      if(!user.name){
        return &lt;div&gt;Hi there.&lt;/div&gt;
      }
      return &lt;div&gt;Hi, my name is {user.name}&lt;/div&gt;;
    }</code></pre>



<h4 class="wp-block-heading">How to Specify an Attribute in JSX</h4>



<p>One more important thing you need to know about writing JSX code are attributes. </p>



<p>Much like HTML attributes may be written and assigned to a JSX element.</p>



<p>For example, consider this image element:</p>



<pre class="wp-block-code"><code>const user = {
  name: "Kris Barton",
  avatar: "img.jpg"
}
const avatar = &lt;img src={user.avatar} alt="This is the user's avatar" tabIndex="0" className="avatar__img" /&gt;</code></pre>



<p>There&#8217;s a bit to unpack here.</p>



<p>Firstly, you will note tabIndex and className. </p>



<p>In regular HTML, this would be <em>tabindex</em> and <em>class</em> respectively. Because JSX is closer to Javascript than HTML, ReactDOM uses the camelCase naming convention. </p>



<p>But don&#8217;t worry: <em>it will get compiled to the attribute name you&#8217;ll be expecting by the time it get&#8217;s to a web browser.</em></p>



<p>Next you will probably note the attributes take two different types of value: a string and a value in curly braces. </p>



<p>Just remember:</p>



<ul>
<li>Attributes can take both strings and expressions. </li>



<li>These attribute curly braces work in the same way as our greeting example above &#8211; as JSX Expressions. So, in the example above the &lt;Img /&gt; element&#8217;s src attribute will compile to <strong><em>&lt;img src=&#8221;img.jpg&#8221; alt=&#8221;This is the user&#8217;s avatar&#8221; tabindex=&#8221;0&#8243; class=&#8221;avatar__img&#8221; /&gt;</em></strong></li>
</ul>



<p>For more information and examples of JSX, <a href="https://reactjs.org/docs/introducing-jsx.html" class="rank-math-link" target="_blank" rel="noopener">check out the React docs</a> and for a little more advanced JSX stuff, check out the <a href="https://reactjs.org/docs/jsx-in-depth.html" class="rank-math-link" target="_blank" rel="noopener">Advanced JSX React docs</a>.</p>



<p>Now let&#8217;s move onto the next React coding concept: Elements.</p>



<h3 class="wp-block-heading">Elements</h3>



<p><a href="https://reactjs.org/docs/rendering-elements.html" class="rank-math-link" target="_blank" rel="noopener">The React documentation</a> goes a great job of describing what elements mean in React:</p>



<blockquote class="wp-block-quote">
<p>&#8220;<strong><em>An element describes what you want to see on the screen</em></strong>&#8220;</p>
</blockquote>



<p>So, from my first JSX example above, the following is an element: </p>



<pre class="wp-block-code"><code>const hello = &lt;h1&gt;Hello, world!&lt;/h1&gt;;</code></pre>



<p>The same as the below chunk of code is an element:</p>



<pre class="wp-block-code"><code>const list = 
&lt;ul&gt;
  &lt;li&gt; Item One &lt;/li&gt;
  &lt;li&gt; Item Two &lt;/li&gt;
  &lt;li&gt; Item Three &lt;/li&gt;
&lt;/ul&gt;</code></pre>



<p>And as you&#8217;ve seen from the CodePen examples above, we render an element by using ReactDOM&#8217;s render method.</p>



<pre class="wp-block-code"><code>const greeting = "Hi, my name's Kris Barton.";
const hello = &lt;h1&gt;Hello, World! {greeting}&lt;/h1&gt;;

ReactDOM.render(hello, document.getElementById('root'));</code></pre>



<p>As you can see, we:</p>



<ul>
<li>Call the ReactDOM&#8217;s render method.</li>



<li>Passes in our element as the first argument.</li>



<li>Then we tell it where to render the element. In this case, in an HTML element that has the id of <strong><em>root</em></strong>.</li>
</ul>



<p>Now let&#8217;s take a look at slightly bigger concept that&#8217;s important for getting started with React: <strong><em>components</em></strong>.</p>



<h3 class="wp-block-heading">Components</h3>



<p>The concept of components isn&#8217;t unique to React, but it&#8217;s a big part of React&#8217;s DNA.</p>



<p>A component-based architecture allows developers to create reusable chunks of code that can easily be reused throughout a website, an app or even on the same web page. </p>



<p>It allows use to create code in isolation that does not need to interact with out components or aspects of the web page they&#8217;re on at all. </p>



<p>Again, the <a href="https://reactjs.org/docs/components-and-props.html" class="rank-math-link" target="_blank" rel="noopener">ReactJS.org documentation perfectly describes components in React</a>:</p>



<blockquote class="wp-block-quote">
<p>&#8220;<strong><em>Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.&#8221;</em></strong></p>
</blockquote>



<h4 class="wp-block-heading">How to Define a Component in React</h4>



<p>In React, component&#8217;s can be defined a couple of different ways.</p>



<p>The first way is pretty much exactly like defining a Javascript function (don&#8217;t worry about props just yet, we&#8217;ll cover that next):</p>



<pre class="wp-block-code"><code>function Hello(props) {
  return &lt;h1&gt;Hey there, {props.name}.&lt;h1&gt;;
}</code></pre>



<p>The second way to define a component is using Javascript ES6:</p>



<pre class="wp-block-code"><code>class Hello extends React.Component {
   render() {
     return &lt;h1&gt;Hey there, {this.props.name}.&lt;/h1&gt;;
   }
}</code></pre>



<h4 class="wp-block-heading">How to Render a Component in React</h4>



<p>We render a component in React pretty much how we&#8217;d rendered an element in the example earlier in the article. </p>



<pre class="wp-block-code"><code>function Hello(props) {
  return &lt;h1&gt;Hey there, {props.name}&lt;/h1&gt;;
}

const greeting = &lt;Hello name="Kris Barton" /&gt;;
ReactDOM.render(
  greeting,
  document.getElementById('root')
);</code></pre>



<p>Let&#8217;s break down the example above: </p>



<ol>
<li>We declare Hello as a component just like we would a regular Javascript function. </li>



<li>We use the props object to grab the <strong>name</strong> attribute and use JSX expressions to add it to the welcome message. More on props later.</li>



<li>Then, we use it like we would an HTML element. We declare the <strong>name</strong> attribute and give that attribute a value.</li>



<li>Then we render the component in our root div using the ReactDOM.render() method.</li>
</ol>



<h4 class="wp-block-heading">Components within Components</h4>



<p>As mentioned earlier in this section, components allow us to break down our User Interface into small chunks.</p>



<p>So, in React we have the ability to use components within components and of course use the same component multiple times.</p>



<p>So using the example above, we abstract our Hello element and add it multiple times (with different names) to another function. Then, we&#8217;ll use ReactDOM to render everything.</p>



<p>That looks a little like this:</p>



<pre class="wp-block-code"><code> function Hello(props) {
  return &lt;h1&gt;Hey there, {props.name}&lt;/h1&gt;;
}
    
    function App() {
      return (
        &lt;div&gt;
          &lt;Hello name="Joe Montana" /&gt;
          &lt;Hello name="Jim McMahon" /&gt;
          &lt;Hello name="Terry Bradshaw" /&gt;
        &lt;/div&gt;
      );
    }

ReactDOM.render(
  &lt;App /&gt;,
  document.getElementById('root')
);</code></pre>



<p>Let&#8217;s take a look at a working version of that code:</p>



<p class="codepen" data-height="500" data-theme-id="light" data-default-tab="html,result" data-user="krisbarton" data-slug-hash="qBaQPjL" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Rendering Components in React">
  <span>See the Pen <a href="https://codepen.io/krisbarton/pen/qBaQPjL" target="_blank" rel="noopener">
  Rendering Components in React</a> by Kris Barton (<a href="https://codepen.io/krisbarton" target="_blank" rel="noopener">@krisbarton</a>)
  on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</span>
</p>
<script async="" src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>



<p>I think that covers components pretty well, let&#8217;s move onto Props.</p>



<h3 class="wp-block-heading">Props</h3>



<p>We&#8217;ve already already used examples of Props earlier in the article and by now you&#8217;ll probably have a good idea what they are.</p>



<p>Here&#8217;s a quick Props overview:</p>



<ul>
<li>Props stands for properties.</li>



<li>Props are arguments that are passed into React Components, which are then used in those React Components. </li>



<li>Props are immutable. Meaning they&#8217;re read-only &#8211; we can display and use them, but not alter them.</li>



<li>Props are just regular Javascript objects.</li>
</ul>



<p>Let&#8217;s take one of the components we created and passed props into in the last Components example.</p>



<pre class="wp-block-code"><code>&lt;Hello name="Joe Montana" /&gt;</code></pre>



<p>Here, we declare an iteration of the <strong>Hello component</strong> and pass <strong>name</strong> into the component as props.</p>



<p>Inside the component, we have access to the value of name by accessing <strong>props.name</strong>. Like this:</p>



<pre class="wp-block-code"><code>function Hello(props) {
  return &lt;h1&gt;Hey there, {props.name}&lt;/h1&gt;;
}</code></pre>



<p>The naming is like for like: so we declare the attribute as <strong>name</strong> and access in the props as <strong>props.name</strong>. If we decided that we wanted to add an age attribute, we&#8217;d declare it like this:</p>



<pre class="wp-block-code"><code>&lt;Hello name="Joe Montana" age="64" /&gt;</code></pre>



<p>And access it using props.age. So let&#8217;s apply this to the component:</p>



<pre class="wp-block-code"><code>function Hello(props) {
  return &lt;h1&gt;Hey there, {props.name}. I'm {props.age} years old.&lt;/h1&gt;;
}</code></pre>



<p>Now let&#8217;s take a look at that in our CodePen.</p>



<p class="codepen" data-height="500" data-theme-id="light" data-default-tab="html,result" data-user="krisbarton" data-slug-hash="GRjPROm" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Adding the Age Props">
  <span>See the Pen <a href="https://codepen.io/krisbarton/pen/GRjPROm" target="_blank" rel="noopener">
  Adding the Age Props</a> by Kris Barton (<a href="https://codepen.io/krisbarton" target="_blank" rel="noopener">@krisbarton</a>)
  on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</span>
</p>
<script async="" src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>



<p>Essentially&#8230;</p>



<blockquote class="wp-block-quote">
<p><strong><em>You can think of props as an object in which of the component attributes are stored.</em></strong></p>
</blockquote>



<p>Now it&#8217;s time to look at another important concept that you absolutely need to know when getting started with React.</p>



<h3 class="wp-block-heading">State</h3>



<p>What is state in React? Here&#8217;s a quick overview:</p>



<ul>
<li>State is a Javascript object that stores all of a component&#8217;s dynamic data and determines behaviour.</li>



<li>When the state object changes, the component re-renders.</li>



<li>State can only be used in a Class component out of the box. For a functional component, <a href="https://reactjs.org/docs/hooks-intro.html" class="rank-math-link" target="_blank" rel="noopener">React Hooks</a> may be used instead.</li>



<li>The state handles the component that it&#8217;s declared and used in.</li>
</ul>



<p>Sounds a bit like a prop, right?</p>



<h4 class="wp-block-heading">What&#8217;s the difference between Prop and State?</h4>



<p>I think the explanation from the <a href="https://reactjs.org/docs/faq-state.html" class="rank-math-link" target="_blank" rel="noopener">React Documentation</a> is the best:</p>



<blockquote class="wp-block-quote">
<p><em><strong>&#8220;</strong><code><a href="https://reactjs.org/docs/components-and-props.html" target="_blank" rel="noopener">props</a></code>&nbsp;(short for “properties”) and&nbsp;<a href="https://reactjs.org/docs/state-and-lifecycle.html" target="_blank" rel="noopener"><code>state</code></a>&nbsp;are both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way:&nbsp;<code>props</code>&nbsp;get passed&nbsp;to&nbsp;the component (similar to function parameters) whereas&nbsp;<code>state</code>&nbsp;is managed&nbsp;within&nbsp;the component (similar to variables declared within a function).</em>&#8220;</p>
</blockquote>



<p>I think a good demonstration of state within a component is a Timer function.</p>



<p>Consider the below React component.</p>



<pre class="wp-block-code"><code>class Timer extends React.Component {
    constructor(props) {
      super(props);
      this.state = {date: new Date() };
    }

   render() {
     return &lt;h1&gt;Current time: {this.state.date.toLocaleTimeString()}.&lt;/h1&gt;;
   }
}
     
ReactDOM.render(
  &lt;Timer /&gt;,
  document.getElementById('root')
);</code></pre>



<p>A couple of things to note:</p>



<ul>
<li>When using a constructor, props have to be passed in using super(props) &#8211;  don&#8217;t worry about this just yet. </li>



<li>We declare the state in the constructor using <strong>this.state</strong> <strong>= {date: new Date()}</strong>.</li>



<li>We display the name using a JSX expression pretty much the same way we did props with <strong>this.state.date</strong>.</li>



<li>We render the component in the exact same way as before &#8211; passing it into ReactDOM.render() and pushing it our div with an id of root.</li>
</ul>



<p>The example above captures the state on page load and renders the output &#8211; in this date the current time.</p>



<p>But state can be updated within a component. Most commonly, this is through user interaction &#8211; a button click, a form input or something like that. </p>



<p>And to do this, we use the <strong>this.setState()</strong> option.</p>



<p>So:</p>



<ul>
<li>We use this.state on initialization in the construction function. i.e. <strong>this.state.date = new date()</strong>.</li>



<li>We use this.setState() to update the state. i.e. <strong>this.setState( date: new date())</strong>.</li>
</ul>



<p>So let&#8217;s update our example above so we change update the time to update in real time.</p>



<pre class="wp-block-code"><code>class Timer extends React.Component {
    constructor(props) {
      super(props);
      this.state = {date: new Date() };
    }
    
    componentDidMount() {
      this.timerId = setInterval(
        () =&gt; this.updateTime(),
        1000
      );
    }
    
    componentWillUnmount() {
      clearInterval(this.timerId);
    }
    
    updateTime() {
      this.setState( { date: new Date() } ) 
    }

   render() {
     return &lt;h1&gt;Current time: {this.state.date.toLocaleTimeString()}.&lt;/h1&gt;;
   }
}
    
ReactDOM.render(
  &lt;Timer /&gt;,
  document.getElementById('root')
);</code></pre>



<p>Let&#8217;s walk through the code a little.</p>



<p>You&#8217;ll notice:</p>



<ul>
<li>We&#8217;ve added a function called updateTime() in which we update the state of the component. i.e. we set it to the current time.</li>



<li>We&#8217;ve added a React Lifecycle method called componentDidMount(). This is a part of the React library and it&#8217;s basically a function that fires when the component is mounted i.e. when the page is first loaded.</li>



<li>In componentDidMount() we&#8217;ve set up a standard Javascript setInterval function that fires our updateTime function every second.</li>



<li>We also used the componentWillUnmount React Lifecycle method that clears the interval. </li>
</ul>



<p>Don&#8217;t worry about the React Lifecycle stuff just yet &#8211; I&#8217;ll cover that in another article later. All you need to know is that the state updates as intended.</p>



<p>Here&#8217;s a working CodePen showing this functionality in action:</p>



<p class="codepen" data-height="500" data-theme-id="light" data-default-tab="html,result" data-user="krisbarton" data-slug-hash="zYKyrGv" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Using State in React">
  <span>See the Pen <a href="https://codepen.io/krisbarton/pen/zYKyrGv" target="_blank" rel="noopener">
  Using State in React</a> by Kris Barton (<a href="https://codepen.io/krisbarton" target="_blank" rel="noopener">@krisbarton</a>)
  on <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a>.</span>
</p>
<script async="" src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>



<h2 class="wp-block-heading">Are You Set For Getting Started With React?</h2>



<p>Hopefully this article has given you a good idea for getting started with React, but remember: the learning doesn&#8217;t stop here. </p>



<p>There&#8217;s a lot more to learn with React, but this article is a great start.</p>



<p>You might be asking yourself: <em>what&#8217;s next?</em> <em>What&#8217;s next for learning React?</em></p>



<p>Next Steps for getting started with React are:</p>



<ul>
<li>Read through the<a href="https://reactjs.org/docs/hello-world.html" class="rank-math-link" target="_blank" rel="noopener"> React Documentation</a> from back to front.</li>



<li>Once you&#8217;ve installed create-react-app as mentioned earlier in this article, pull it apart and try to see how it all hangs together.</li>



<li>Come back and check out more <a href="https://www.thewebdeveloperguide.com/articles/" class="rank-math-link">React articles here</a>.</li>
</ul>



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



<p>Below is a list of resources we&#8217;ve used in our Getting Started with React article:</p>



<ul>
<li><a href="https://reactjs.org/docs/getting-started.html" class="rank-math-link" target="_blank" rel="noopener">ReactJS Documentation</a>.</li>



<li><a href="https://reactjs.org/tutorial/tutorial.html" class="rank-math-link" target="_blank" rel="noopener">ReactJS Tutorials</a>.</li>



<li><a href="https://create-react-app.dev/docs/getting-started/" class="rank-math-link" target="_blank" rel="noopener">Create React App</a>.</li>
</ul>
]]></content:encoded>
					
		
		
			</item>
		<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" loading="lazy" 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>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>
		<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>
