<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohammedtaitai on Medium]]></title>
        <description><![CDATA[Stories by Mohammedtaitai on Medium]]></description>
        <link>https://medium.com/@mohammedtaitai?source=rss-f326b96c41d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MTeyB3HC3xuCIOwAuPk6AA.jpeg</url>
            <title>Stories by Mohammedtaitai on Medium</title>
            <link>https://medium.com/@mohammedtaitai?source=rss-f326b96c41d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:55:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohammedtaitai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ruby Local Variables, Instance Variables, and Class Variables: A Brief Overview]]></title>
            <link>https://medium.com/@mohammedtaitai/ruby-local-variables-instance-variables-and-class-variables-a-brief-overview-e558876886de?source=rss-f326b96c41d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e558876886de</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Mohammedtaitai]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 19:42:39 GMT</pubDate>
            <atom:updated>2023-06-15T20:30:19.354Z</atom:updated>
            <content:encoded><![CDATA[<p>When programming in Ruby, it’s crucial to understand the different types of variables available and how they are used within the language. We’ll explore three types of variables: local variables, instance variables, and class variables.</p><h4>Local Variables</h4><p>Local variables are used to store temporary data within a specific scope like a method or a block. When defining a local variable start the variable name with a lowercase letter. Local variables are only accessible within the block or method they are defined in.</p><pre>def greet<br>  name = &quot;John&quot;<br>  puts &quot;Hello, #{name}!&quot;<br>end<br><br>greet</pre><p>For example, the name variable is a local variable that stores the string &quot;John.&quot; It is only accessible within the greet method.</p><h4>Instance Variables</h4><p>Instance variables are preceded by a single @ symbol and are used to store data that is specific to an instance of a class. The value of an instance variable is local to the specific instance of a class.</p><pre>class Person<br>  def initialize(name)<br>    @name = name<br>  end<br><br>  def greet<br>    puts &quot;Hello, #{@name}!&quot;<br>  end<br>end<br><br>person = Person.new(&quot;Alice&quot;)<br>person.greet</pre><p>For example, the @name variable is an instance variable, which holds the name of a person. It is accessible within the initialize method as well as the greet method.</p><h4>Class Variables</h4><p>Class variables are preceded by two @ symbols and are used to store data that is shared among all instances of a class. Class variables can be accessed within the class they are defined in as well as instance methods and child classes.</p><pre>class Counter<br>  @@count = 0<br><br>  def initialize<br>    @@count += 1<br>  end<br><br>  def self.total_count<br>    puts &quot;Total count: #{@@count}&quot;<br>  end<br>end<br><br>counter1 = Counter.new<br>counter2 = Counter.new<br><br>Counter.total_count</pre><p>In the above example, the @@count variable is a class variable that keeps track of the total number of instances created. Each time a new instance of the Counter class is created, the initialize method increments@@count by one. The total_count method is a class method that prints the total count.</p><p>Understanding the differences between local variables, instance variables, and class variables is crucial when writing effective Ruby code. By using the appropriate variable types in the right contexts, you can ensure your code is clean, organized, and easy to maintain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e558876886de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Sinatra with ActiveRecord in Ruby: A Powerful Combination for Web Development]]></title>
            <link>https://medium.com/@mohammedtaitai/using-sinatra-with-activerecord-in-ruby-a-powerful-combination-for-web-development-c0ab1dbce3c1?source=rss-f326b96c41d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0ab1dbce3c1</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[sinatra-app]]></category>
            <category><![CDATA[sqlite3]]></category>
            <category><![CDATA[activerecord]]></category>
            <dc:creator><![CDATA[Mohammedtaitai]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 04:44:35 GMT</pubDate>
            <atom:updated>2023-06-05T04:44:35.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Sinatra and ActiveRecord are two popular frameworks in the Ruby ecosystem that can be combined to create robust web applications. In this blog post, we’ll explore how to use Sinatra with ActiveRecord, leveraging the power of a lightweight web framework and a flexible ORM (Object-Relational Mapping) tool. We’ll cover the setup process, defining models, performing database operations, integrating ActiveRecord with Sinatra routes, and touch on additional features. Let’s dive in!</p><h4>Setting up Sinatra and ActiveRecord</h4><p>To get started, make sure you have Sinatra and ActiveRecord gems installed in your Ruby environment. Sinatra is a lightweight web framework, and ActiveRecord is an ORM that simplifies database interactions. Add the following lines to your Gemfile and run bundle install:</p><pre>gem &#39;sinatra&#39;<br>gem &#39;activerecord&#39;<br>gem &#39;sqlite3&#39; # Use a different adapter if needed</pre><p>Next, create a basic Sinatra application file (app.rb) and require the necessary dependencies:</p><pre>require &#39;sinatra/base&#39;<br>require &#39;sinatra/activerecord&#39;</pre><pre># Configure the database connection<br>set :database, &#39;sqlite3:database.db&#39;</pre><pre># Your Sinatra application code goes here</pre><h4>Defining models and database migrations:</h4><p>In Sinatra with ActiveRecord, models are used to define the structure and behavior of your database tables. Let’s create a simple “User” model as an example:</p><pre>class User &lt; ActiveRecord::Base<br>  # Define associations, validations, and other model logic here<br>end</pre><p>To create the corresponding database table, we’ll use ActiveRecord migrations. Create a new migration file with a descriptive name (e.g., 001_create_users.rb) in a db/migrate directory:</p><pre>class CreateUsers &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    create_table :users do |t|<br>      t.string :name<br>      t.string :email<br>      t.timestamps null: false<br>    end<br>  end<br>end</pre><p>Running the migration is as simple as running rake db:migrate. This will create the &quot;users&quot; table with the specified columns.</p><h4>Using ActiveRecord in Sinatra routes</h4><p>Now that we have our models and database set up, let’s see how to use ActiveRecord within Sinatra routes. Here’s an example of a basic route that fetches all users from the database:</p><pre>get &#39;/users&#39; do<br>  users = user.all<br>listing.to_json<br>end</pre><p>In this example, User.all retrieves all user records from the &quot;users&quot; table. The resulting collection is then passed to where the request comes from allowing whoever requested the information to render it how they please.</p><h4>Creating a One-to-Many Relationship</h4><p>A one-to-many relationship is a common scenario where one record in a table is associated with multiple records in another table. In the context of our property listings manager app, let’s assume we have a “Property” model and a “ListingAgent” model. Each property can have multiple listing agents.</p><ol><li>Define the Models: Start by defining the models for the Property and ListingAgent. In your respective model files (property.rb and listing_agent.rb), you can set up the one-to-many association using the has_many and belongs_to methods:</li></ol><pre># property.rb<br>class Property &lt; ActiveRecord::Base<br>  has_many :listing_agents<br>  # Other property model logic<br>end</pre><pre># listing_agent.rb<br>class ListingAgent &lt; ActiveRecord::Base<br>  belongs_to :property<br>  # Other listing agent model logic<br>end</pre><ol><li>Add Foreign Key: To establish the relationship, you’ll need to add a foreign key column to the table that represents the “many” side of the association. In our case, we need to add a property_id column to the listing_agents table. To achieve this, create a migration file (e.g., 002_add_property_id_to_listing_agents.rb) in the db/migrate directory:</li></ol><pre>class AddPropertyIdToListingAgents &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    add_column :listing_agents, :property_id, :integer<br>  end<br>end</pre><p>Then, run the migration with the rake db:migrate command.</p><ol><li>Update the Forms and Routes: To associate a listing agent with a property, you need to update the forms and routes accordingly. For example, when creating a new listing agent, you can include a select input field to choose the associated property. In the route handling the form submission, you can then assign the selected property to the listing agent:</li></ol><pre>post &#39;/listing_agents&#39; do<br>  @listing_agent = ListingAgent.new(params[:listing_agent])<br>  @listing_agent.property = Property.find(params[:property_id])<br>  <br>  if @listing_agent.save<br>    redirect &#39;/listing_agents&#39;<br>  else<br>    erb :new_listing_agent<br>  end<br>end</pre><ol><li>Accessing the Associated Records: With the one-to-many relationship established, you can access the associated records from either side. For example, to retrieve all listing agents associated with a specific property, you can use the listing_agents association method:</li></ol><pre>get &#39;/properties/:id/listing_agents&#39; do<br>  @property = Property.find(params[:id])<br>  @listing_agents = @property.listing_agents<br>  <br>  property_listing_agents.to_json<br>end</pre><p>In this example, we find the property based on the provided id parameter and then access the associated listing agents using the listing_agents method.</p><h4>Additional Features</h4><p>Sinatra and ActiveRecord offer many additional features that enhance the development process. Here are a few notable ones:</p><ol><li>Routing: Sinatra provides a clean and intuitive syntax for defining routes and handling HTTP requests. You can create routes for different URLs, HTTP methods, and route parameters.</li></ol><p>2. Validations: ActiveRecord provides built-in validation methods to ensure data integrity. You can validate model attributes, such as presence, uniqueness, format, and more.</p><p>3. Associations: ActiveRecord enables you to define relationships between models, such as one-to-one, one-to-many, and many-to-many. This makes it easy to work with related data and perform queries across associations.</p><h4>Conclusion</h4><p>Combining Sinatra with ActiveRecord provides a powerful foundation for building web applications in Ruby. Sinatra’s simplicity and flexibility complement ActiveRecord’s ability to interact with the database, allowing you to focus on writing clean and maintainable code. In this blog post, we covered the setup process, defining models, performing database operations, integrating ActiveRecord with Sinatra routes, and briefly touched on additional features. Armed with this knowledge, you can leverage the best of both frameworks to create robust web applications efficiently.</p><p>For more information on Sinatra visit: <a href="http://sinatrarb.com/">http://sinatrarb.com/</a>. For more information on ActiveRecord visit <a href="https://guides.rubyonrails.org/active_record_basics.html">https://guides.rubyonrails.org/active_record_basics.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0ab1dbce3c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Ruby Classes]]></title>
            <link>https://medium.com/@mohammedtaitai/building-ruby-classes-69f3f4353596?source=rss-f326b96c41d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/69f3f4353596</guid>
            <category><![CDATA[classes-and-objects]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Mohammedtaitai]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 21:13:14 GMT</pubDate>
            <atom:updated>2023-01-20T21:13:14.904Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby is an object-oriented language based around objects. Every value, data type, and method is an object. Like most object-oriented programming, one can create a data type called a class. A class is a custom data type that allows us to create our own objects. Think of it as a blueprint to describe the different attributes an object will have. For instance, you can create a class called Actors which can create an actor object. This object can hold all the information about the actor like age, relationship status, movies, etc as well as different methods to manipulate the data.</p><h3><strong>How to create a class</strong></h3><p>Let&#39;s create an actor class. To begin defining a class, we start by using the keyword class followed by the name. Make sure to capitalize the class&#39;s name. Like other methods in Ruby, you need to make sure you end the class with end .</p><pre>class Actors<br><br>end</pre><p>you now have a class to build objects from. To create a new object you assign the name of the object to the class name with .new after it.</p><pre>objectname = Actors.new;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kahPJOytWWQUQ6oHvyMj9g.png" /></figure><p>But right now the object has no data or attributes.</p><h4>Setter and getter methods</h4><p>In order to add some you need to create a setter and getter method. As the name implies, these methods set and get the data in the object. Let&#39;s say we want to add the actor&#39;s latest movie. We need to assign a value to the instance variable of the latest movie. The instance variable is the attribute of the object in that instance of the class. To create the setter method we add a method to the class that takes whatever parameter you want to set to the variable. Make sure to set add a = between the parameter and the method name. In the method you set the instance variable, using an @, equal to the parameter.</p><pre>class Actors<br>  def latestMovie(lastMovie)<br>    @latestMovie = lastMovie<br>  end<br>end</pre><p>The getter method is similar to the setter but since it&#39;s the method that returns information, there is no need for any parameters or assignment.</p><pre>class Actors<br>  def latestMovie<br>    @latestMovie<br>  end<br>end</pre><p>Finally, we can pass through the data that we want. Set data by passing it through the setter method of the object you want to add the data to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77Xr2sqyCx0eIsHxcE-U4g.png" /></figure><p>But Ruby is about simplicity. Is there a faster way to do especially if you want to add more than one variable to the object?</p><h4>Attribute accessors</h4><p>Ruby has 3 macros that simplify the process of setting and getting data. attr_reader , attr_writer , and attr_accessor . Using these macros removes the need to write a method to access the instance variables.</p><pre>class Actors<br><br>  attr_reader :latestMovie<br>  # similar to<br>  # def name<br>  #   @name<br>  # end<br><br>  attr_writer :latestMovie<br>  # similar to<br>  # def name=(value)<br>  #   @name = value<br>  # end<br><br>end</pre><p>To make matters even easier you can use attr_accessor which is similar to writing attribute reader and writer.</p><pre>class Actors<br><br>  attr_accessor :latestMovie<br><br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NoBif6tRVNSj-sW6QOfBw.png" /></figure><h4>Initialize</h4><p>On the theme of cutting down on the amount of code we are writing we are writing, classes can have an initialize method that can help assign data to instance variables when the object is created. Let&#39;s add an age variable to our actor class.</p><pre>class Actors<br>    attr_accessor :latestMovie, :age<br><br>end</pre><p>From here we create a method called to initialize and pass through the data we want the object to have. Then we assigned the instance variable the parameters that were passed through as we did with the setter method.</p><pre>class Actors<br>    attr_accessor :latestMovie, :age<br><br>    def initialize(lastMovie, age)<br>        @age = age<br>        @latestMovie = lastMovie<br>    end<br>end</pre><p>Now when we create a new object we can pass the values we want the object to have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2OPoUPSUlduaPwjWhxB1A.png" /></figure><h4>Class Variables and Methods</h4><p>The last thing we’ll go over is class variables and methods. These are attributes or variables that are can be accessed by calling the class itself. In the case of our actors class, we can have a variable that keeps track of the number of actors. To define a class variable we use two @ in fronts of the variable name.</p><pre>class Actor <br>  @@actorCount = 0<br><br>end</pre><p>Now we have a class variable but we haven&#39;t done anything with it yet. Let&#39;s increase the count every time an object is initialized.</p><pre>class Actors<br>    @@actor_count = 0<br><br>    attr_accessor :age<br><br>    def initialize(age)<br>        @age = age<br>        @@actor_count += 1<br>    end<br><br>end</pre><p>Last we need to be able to return the class variable. To do this we need to make a class method. We use the self keyword when creating a class method in reference to the class itself followed by the method name.</p><pre>def self.count<br>  @@actor_count<br>end</pre><p>Now every time we create an actor object, the class keeps track of how many objects there are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjrRJy4U-H5tKAMQcnhqeg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69f3f4353596" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Router Basics]]></title>
            <link>https://medium.com/@mohammedtaitai/react-router-basics-7392575389f6?source=rss-f326b96c41d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7392575389f6</guid>
            <dc:creator><![CDATA[Mohammedtaitai]]></dc:creator>
            <pubDate>Wed, 26 Oct 2022 23:47:03 GMT</pubDate>
            <atom:updated>2022-10-27T03:27:06.352Z</atom:updated>
            <content:encoded><![CDATA[<p>The single-page application generally refers to when an application or website is made with a single HTML file. This results in fewer requests for the clients meaning faster loading times. Many applications and websites you use now are made on single-page applications like Netflix, Airbnb, and Paypal. One of the tools used to help create a single-page application is React Router.</p><p>React Router is a package that helps navigate the different components is a web application by rendering them based on what is written in the URL. For instance, www.PizzaShoppe.com/ would render the landing page for a pizza company while <a href="http://www.pizzashoppe.com/order">www.PizzaShoppe.com/order</a> would render the ordering component without having to request a separate HTML file. When you are in the folder of the project you want to use react-router in run:</p><pre>npm install react-router-dom</pre><p>while in the terminal. This will download the package in order to start using routes.</p><h4>Using react-router</h4><p>After the package is installed you would start by going to the very top of your component hierarchy. This is generally the .js file you have embedded in your script attribute in the HTML file. Here you will import the BrowserRouter component from react-router-dom.</p><pre>import { BrowserRouter } from “react-router-dom”;</pre><p>Long story short, this component will help keep track of all the component&#39;s URLs. To use this component we want to wrap the Application or next component in the hierarchy in the BrowserRouter component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*kRtUK2NGHu_S8CKhn9023A.png" /></figure><p>In the app component, you will want to import the Route and Switch components.</p><pre>import { Route, Switch } from &quot;react-router&quot;;</pre><p>The Route component will help specify which component to render based on the URL. The Switch component acts like a switch statement for the Routes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*kI9I6aF8EMgORLWVi_MwAA.png" /></figure><blockquote>Many home routes are set with and empty / path since many default URL end in with nothing after the forward slash like <a href="https://medium.com/">https://medium.com/</a>.</blockquote><p>For this example when the URL ends with /income the Income component is rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhrmdgErrR9x0AWLSQ_8nQ.png" /></figure><p>One issue that may arise is typing in a path that is not one of the options for instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpHSMxflYwZxow1C32z0ng.png" /></figure><p>As you can see if a path does not match any of the component paths, the app component will render the home component. One way to fix this would be add an exact prop to the home path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*zVzYDYb_tvLcPaBrfQrcbw.png" /></figure><p>This way the home component is only render when the URL ends in /.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdQ6JTJKvp0OFI-IFNiWaQ.png" /></figure><p>But that does not the best we need some way to tell the user that the path is not correct. Adding another route as a catch-all would be a good way to do that. Adding an asterisk to this new route path will render the same thing for everything that does not match the other paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*9cTiD0QYlWitU3YOPpEuXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmwQ6IbLdQgnV1D3vcP1aQ.png" /></figure><p>No one wants to navigate an application or website by typing in the URL all the time. In the next section, we’ll learn to use a navigation bar to navigate through the components.</p><h4>Utilizing Link in React Router</h4><p>With multiple HTML pages, one would use an &lt;a&gt; tag in the nav bar to jump between the pages. With react-router we can the Link component to change the URL. To start import the link component into which ever component you want to render you navigation bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*KbW7ZGUOkOIsGIrqSs5mkw.png" /></figure><p>Then you would use the Link component like you would an anchor tag in your JSX. use the To prop to specify the path you want in the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*JDslsUsveo2G-QhqtqUJ2Q.png" /></figure><p>React router also has one more trick. If you would like to show the user which link is currently active you can use the NavLink component. To implement follow the same steps as the link component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*1cxtU4uLhMn1dWBtVs3i3A.png" /></figure><p>From here you can now add a :active CSS attribute that will only be applied to when the client is on that path. Again, make sure to use exact on you home page so that the program does not add the active class to multiple NavLink components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*yyNNDGZmmYYDQU2GDJz4OQ.png" /></figure><h4>Conclsion</h4><p>One may say, “ All that can be done using state hooks.” All though its true you can save your self a significant amount of time and effort by useing React router. This package cuts the amount of writing you need to make in half.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7392575389f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dom Manipulation-Selecting Elements]]></title>
            <link>https://medium.com/@mohammedtaitai/dom-manipulation-selecting-elements-9f32457cb524?source=rss-f326b96c41d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f32457cb524</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[elements]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[dom-manipulation]]></category>
            <dc:creator><![CDATA[Mohammedtaitai]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 01:25:44 GMT</pubDate>
            <atom:updated>2022-07-02T01:25:44.686Z</atom:updated>
            <content:encoded><![CDATA[<p>In everyone’s beginning phases of learning frontend development, one will come across the topic of DOM manipulation. Being able to manipulate a DOM is one of the basics when it comes to making a dynamic website. Adding an event listener to a webpage can help spice up a web page and some can even make games out of it.</p><h4>Find the element</h4><p>First thing is first, you need to know what element you want to manipulate. This is as easy as looking at the document, the HTML you are wanting to manipulate, and picking the element name you are wanting to manipulate. If you are working on a completely static website with hundreds of lines of code there is an easier way to do this.</p><ol><li>Right-click on the web page in the browser, and click inspect.</li><li>Click the elements tab.</li><li>In the top left corner of the developer&#39;s tools there is a button with a mouse icon, click it.</li><li>Hover over the element you want on the webpage.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b77gKfWR4F6xQoWcpUbFCw.png" /></figure><p>A big part of being able to manipulate the DOM is selecting the element of in the HTML that you want to manipulate. Just about every element can be picked. Today you’re going to learn five methods of selecting these elements. Those methods are:</p><ul><li><em>querySelector</em></li><li><em>querySelectorAll</em></li><li><em>getElementById</em></li><li><em>getElementsByClassName</em></li><li><em>getElementsByTagName</em></li></ul><p>Remember, in order for your code to find the elements, the script must come after the document has loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*4NxpRdee9FmoIV9z042qsA.png" /></figure><p>If you like to keep all your scripts at the top of your HTML you can use defer them in the tag. This makes sure that your script loads after the HTML does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*rBeYTqD6rVWN4OzgMe-8Hw.png" /></figure><p>To start with selecting an element you need to tell the consol that you are selecting an element from the HTML <em>document. </em>You start by typing document to get access to everything in the HTML file. After that, you&#39;ll chain whatever method you are wanting to use.</p><h4>querySelector()</h4><p>One of the most basic ways to start selecting your elements is with querySelector(). This method will query through the document and return the first tag that matches the argument passed. Using console.log() is a good way to make sure you are selecting the correct element. When passing the tag as the argument in querySelector() remember to put the tag in quotes.</p><p>document.querySelector(&#39;tagName&#39;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTcG34m8llzACG2qDnUKwA.png" /></figure><p>As you can see this selects the entire element including all the elements inside of it. This can be problematic if you&#39;re wanting just to change a particular div element. The querySelector() the method allows you to specify which element you want by typing the class or Id that the element has.</p><p>document.querySelector(&#39;.className&#39;)</p><p>document.querySelector(&#39;#idName&#39;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVpAFzIbu352UidmB3lA7w.png" /></figure><p>Remember that the method will return the first element that has that class, so if your using that class on multiple elements you may not get the element you want. In that case, you may want to use an element Id since Ids are supposed to be unique. Some find querySelector() being the only method you need however JavaScript has other methods to help you select the element you want.</p><h4>querySelectorAll()</h4><p>Similar to querySelector() , querySelectorAll() will return an element based on the tag name, class, or id. The difference is you will get an array-like structure with all the elements that have that argument that is passed.</p><p>document.querySelectorAll(&#39;tagName&#39;)</p><p>document.querySelectorAll(&#39;.className&#39;)</p><p>document.querySelectorAll(&#39;#idName&#39;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhKfbJEtU6Y7a5o3Ugmmug.png" /></figure><p>You can specify which item in the collection you would like the console to return by specifying the index of the array.</p><p>document.querySelectorAll(&#39;tagName&#39;)[0]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXiM3BxMIr51Z1O-B9YkGQ.png" /></figure><h4>getElementById()</h4><p>Similar to querySelector() , getElementById() returns the element with the id that is passed as an argument. The difference is you do not need to pass the CSS selector (#).</p><p>document.getElementsById(&#39;id&#39;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3XoJckqF2rtA3ITdK9bsg.png" /></figure><h4>getElementsByClassName() and getElementsByTagName()</h4><p>Like querySelectorAll() getElementsByClassName() and getElementsByTagName() return an array like object of all the elements that match the argument passed. When you use getElementsByClassName() you do not need to pass the CSS selector (.).You can also specify which item in the collection you would like the console to return by specifying the index of the array and chaining it after the parenthese.</p><p>document.getElementsByClassName(&#39;className&#39;)</p><p>document.getElementsByTagName(&#39;tagName&#39;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eX2O-JqoW_t_2dwVDHC2bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Snwh74S34Z7qnGvJsQtwCw.png" /></figure><h4>To Wrap up</h4><p>When you are writing you code remember that console.log()is your best friend. This will make sure you are selecting the correct element.Some of these methods you may never use in your coding career however its good to know about the different methods. The method starting with “getelementby” are newer methods so there may be a rare occasion in which you can not use them. From here you can assign the elements to variables and manipulate the DOM in many ways.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f32457cb524" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>