Document Object Model And jQuery

A.Document Object Model (DOM):

The DOM will allow us to interface our Javascript code to interact with HTML and CSS. Browsers will construct the DOM, which basically means storing all the HTML tags as Javascript objects.

Go to a website and in the console type: document. That will return the HTML text of the page.

To see the actual objects use: console.dir(document)

This DOM will allow us to use Javascript to interact with the web page. The DOM is enormous, most developers won’t use all the properties.

1.DOM Interaction :

How to grab large groups of elements, like the entire body or head of the HTML, And then focus on grabbing specific HTML items, like classes or ids. Here are some important document attributes:

  1. document.URL — This is the actual URL of the website
  2. document.body — This is everything inside of the body
  3. document.head — This is everything in the head of the page
  4. document.links — These are all the links on the page

For example :

document.URL
document.head

There are many methods for grabbing elements from the DOM:

  1. document.getElementById() — Returns the element with the id
  2. document.getElementsByClassName() — Returns list of all elements belonging to a class
  3. document.getElementsByTagName() — Returns list of all elements with the tag
  4. document.querySelector() — Returns the first object matching the CSS style selector
  5. document.querySelectorAll() — Returns all objects matchin the CSS style selector

The difference between querySelector() and querySelectorAll() is that
querySelectorAll() will return a list of all matches, querySelector() just
returns the first match.

document.getElementById()
document.querySelector()

Q. How to interact and modify the properties?

Grab the value of tag or id or class, then assign it to a variable and then use inbuilt functions to modify them. Once you have grabbed an element, you can interact with it! 

  1. myvariable.style.color (Many CSS options)
  2. myvariable.textContent
  3. myvariable.innerHTML
  4. myvariable.getAttribute()
  5. myvariable.setAttribute()

For example if you want to modify your head tag to red color,

Now if we want to edit actual HTML or text or attributes we can use different methods. If you want to change the text, HTML content, or attributes you can use the following:

  1. myvariable.textContent – This returns just the text
  2. myvariable.innerHTML – This returns the actual html
  3. myvariable.getAttribute() – This returns the original attribute
  4. myvariable.setAttribute() – This allowed you to set an attribut

For example, if you want to modify the paragraph tag.

To modify a particular inner HTML code, you will first querySelector to reach outer tag and then use it again to reach inner HTML code.

var special = document.querySelector("#id")
var specialA = y.querySelector("a")
specialA.getAttribute("href")
specialA.setAttribute("href","https://www.google.com")

2.Event Listener

Many times we only want the interaction to occur on a particular event, such as a click or a hover. The javascript will be “listening” for an event to occur and then execute a function when it happens.

Listening for an event looks like this:

myvariable.addEventListener(event,func);

An example:

var head = document.querySelector(‘h1’);
head.addEventListener(“click”,changeColor);

There are many, many possible events! 

  • Clicks
  • Hovers
  • Double Clicks
  • Drags
  • Much More!

For more information, https://developer.mozilla.org/en-US/docs/Web/Events

For example,

HTML code,

<h1 id='two'>Click Me!</h1>
<h1 id='three'>Double Click Me!</h1>

JS code,

var headTwo = document.querySelector('#two')
var headThree = document.querySelector('#three')
// On Click
headTwo.addEventListener("click",function(){
  headTwo.textContent = "Clicked On";
  headTwo.style.color = 'blue';
})

// Double Click
headThree.addEventListener("dblclick",function(){
  headThree.textContent = "Double Clicked!";
  headThree.style.color = 'red';
})

Here is what you can do with this knowledge, https://github.com/kakabisht/Web-Dev-Blog-UI

For more information,

  1. https://www.w3schools.com/js/js_htmldom.asp
  2. https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model

B.jQuery :

jQuery is a Javascript Library. It is just a large single .js file that has many pre-built methods and objects that simplify your workflow. Specifically interacting with the DOM and making HTTP requests (AJAX)

When jQuery was created, the more robust and convenient methods such as .querySelector() didn’t exist!, jQuery was created as a way to help simplify interactions with the DOM. One of its main features is the use of “$”.

So how do we get jQuery?

1.Link a CDN hosted file (like we did for bootstrap), https://code.jquery.com/

<script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>

2.Download the .js file from jQuery’s official website, https://jquery.com/

Difference between jQuery and Vanilla, Using coding examples.

1.jQuery

var divs = $('div');

$(el).css('border-width', '20px');

$(document).ready(function(){ //code });


2.Vanilla

var divs = document.querySelectorAll('div');

el.style.borderWidth = '20px';

function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

1.Basic jQuery :

To see if jQuery has been installed or not, just type “$” in the browser console,

You can use the $ sign to select elements from the DOM! It will feel a lot like selecting using querySelectorAll().

For example:

  1. Selecting all a tags:
    1. $(‘a’)
  2. Selecting all elements from the class “container”
    1. $(“.container”)
  3. Selecting all elements with id “special”
    1. $(“#special”)

Q. How to interact and modify the properties?

Grab the value of tag or id or class, then assign it to a variable and then use inbuilt functions to modify them. Once you have grabbed an element, you can interact with it!

var x = $('h1');
x.css("color",'red');
x.css("background","blue");

You can also, create an object with jQuery

var newCSS = {
  "color":"white",
  "background":"blue",
  "border":"red"
}
x.css(newCSS);

Q.How to work with multiple tags ?

It stores all the information of tags in an list not an array,

var listItems = $('li');

// Change all items:
listItems.css("color",'red');

// Grab a particular index item:
listItems.eq(0).css('color','blue');

Q.How to change text ?

First grab it and then change it using methods,

// Grabbing Text
$('h1').text()

// Changing Text:
$('h1').text("Brand New Text!")

// Grabbing HTML
$('h1').html()

// Changing HTML
$('h1').html("<em>Now in Italics</em>")

You can also work with attributes,

// Changing an attribute
$("input").eq(1).attr('type','checkbox');

// Changing values
$("input").eq(0).attr('value',"BRAND NEW VALUE");

// Can do this morevar listItems = $('li');

// Change all items:
listItems.css("color",'red');

// Grab a particular index item:
listItems.eq(0).css('color','blue'); directly:
$("input").eq(0).val("cleared up");

We can also add a class with jQuery,

Instead of Using Add and Remove class, I prefer to use Toggle class


// Add a Class
$('h2').addClass("turnRed")

// Remove a Class
$("h2").removeClass("turnRed");

// Toggle the Class on and Off
$("h3").addClass("turnBlue");

$("h3").toggleClass("turnBlue");

2.jQuery Events :

You can use basic event functions similar to DOM, an example will be on click.

For more information, https://api.jquery.com/category/events/

// On Click
$('h1').click(function(){
  console.log("There was a click!");
})

You can also change the content of the header,

$('h3').click(function() {
  $(this).text("I was changed!");
})

You can also use a key press method, which I found interesting. For example the use of enter key,

// Each Keyboard Key has a Keycode, for example Enter is //13, .which tells value of keys on keyboard
$('input').eq(0).keypress(function(event) {
  if(event.which === 13){
    $('h3').toggleClass("turnRed");
  }
})

You can also use animation in jQuery, for more information on that topic https://api.jquery.com/animate/

An example of it would be fade out,

$('input').eq(1).on("click",function(){
  $(".container").fadeOut(3000) ;
})

Now Using HTML + CSS + jQuery + DOM, we can make a connect 4 game,

Now to summaries the importance of DOM and jQuery,

For more information,

  1. https://developer.mozilla.org/en-US/
  2. https://www.w3schools.com/
  3. My GitHub repository

Previous blog containing HTML+CSS+JavaScript :

https://programmerprodigy.code.blog/2020/06/24/javascript-basics-for-web-development/

Advertisement

One thought on “Document Object Model And jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s