---
# System prepended metadata

title: TINKER - Javascript Part 0

---

TINKER - Javascript Part 0
==========================
:::success
groupmember: Moira, Yiran, Estelle, Jiayi
:::

## Developer Tools
-   What seems to be the difference between what gets printed in the console when you do `console.log` vs `console.dir` ? Hint: click on the caret that appears before the output with the `console.dir`.

:::info

- When you have `console.log`, it will show us the original html code contains "#catBadge". As you can see below: 
![console.log code](https://i.imgur.com/KfrOseo.png)

- When you have `console.dir`, it will show us lots more information related to the "#catBadge". This is how computer runs the code and massive information incldues properties of the element, hierarchy syntax (parent/child/nesting) relationship and so on. 
![](https://i.imgur.com/sKX0BZ9.png) 

For example, it indicates the "draggable" property for this element is `false`. 
![](https://i.imgur.com/5PI84fb.png)

:::

-   In the `Elements` tool right-click on the `#catBadge` and do `Copy > Copy Selector`. Paste it somewhere - what do you get? Try this with another element.

:::info

Once I copied the selector, and then typed it into the console.log(), it will apperar the content of the `catBadge`. When I tried to copy other selectors, it will appear content of that selector. 

:::

-   Based on your tinkering around with this tool, can you make any inferences about the code and how it works?  
:::info
By copying the selector, it will help us to save lots of time if we need to "grabe" the correct target element. This will also benefit us for having lesser typo that may appear in the coding. 

:::
      
    


[ ](#Elements-as-HTML-vs-JS-Objects "Elements-as-HTML-vs-JS-Objects")Elements as HTML vs JS Objects
---------------------------------------------------------------------------------------------------

Given that, let's look at a single representation of an element as an object, how we'd find it in the DOM.

```javascript=
let el = {
  tagName: "DIV",
  id: "myID",
  className: "business-card",
  textContent: "TC"
}
```

Note that the element object is the `{ ... }` stuff. It exists regardless of whether it's assigned to a variable or not. But we need a way to reference it in order to do things with it. As such, let's assign it to a variable we can reference. A common *convention* used is to name elements `el` which is short for element.


<br>








### [ ](#Tinker-Activity-Stuff1 "Tinker-Activity-Stuff1")Tinker Activity Stuff:

What JS code do you need to write and execute in order to:

-   GET the class name of the element?
:::info
`el.className`
```javascript=
console.log (el.className);
```

:::
-   READ the text content of the element?
:::info
`el.textContent`
```javascript=
console.log (el.textContent);
```

:::
-   CHANGE the ID of the element to “ABC123”?
:::info
```javascript=
el.id =  “ABC123”;
```

:::
-   WRITE/REPLACE the text “Teachers College, Columbia U.” to this element?
:::info
```javascript=
el.textContent = “Teachers College, Columbia U.”
```

:::
-   ADD (not replace) a class “special” to the element?  
:::info
```javascript=
el['special'] = true; 

if this also work? 
el.push("special"); 
```

:::



---

### [ ](#Objects-in-Objects---Analogy-to-Document-Object-Model "Objects-in-Objects---Analogy-to-Document-Object-Model")Objects in Objects - Analogy to Document Object Model

If the document object model is a giant object, with nested objects - each object representing an element, then we can make an analogy to something like this.

Here we have Harry Potter (the giant root object) and he has friends which are children objects nested in a list under the property `friends`. This structure repersents a relationship between them in a hierarchical way.

> Harry Potter HAS friends.

```
// Representing relationships - like a document object model
{
  name: "Harry Potter",
  alive: true,
  birthYear: 1980,
  friends: [
    {
      name: "Voldemort",
      alive: false,
      birthYear: 1926
    },
    {
      name: "Hermione",
      alive: true,
      birthYear: 1979
    }
  ]
}

```

One special note here:

-   The value of `friends` is NOT two things (i.e. !2 friend objects)
-   The value of `friends` is a SINGLE array-like list (i.e. datatype)
-   If I ask what is the value of `friends` it is an Array-like data thing with a length of two (i.e. 2 friend objects.)
-   So there is a difference between GETTING the value of `friends` and getting a specific friend object in that list. Since we’re working with an array-like list, you can use numerical indexes to reference a specific object in that list. E.g. `object.friends[0]` vs. `object.friends[1]`

### [ ](#Tinker-Activity-Stuff2 "Tinker-Activity-Stuff2")Tinker Activity Stuff:

Now lets revisit and imagine the DOM, represented as a giant nested JS Object with each object representing an element and its property/values.

```javascript
let el = {
  tagName: "DIV",
  id: "myID",
  className: "business-card",
  children: [
    {
      tagName: "IMG",
      src: "http://myphoto.com"
    },
    {
      tagName: "A",
      href: "http://mywebsite.com",
      textContent: "My Name"
    }
  ]
}

```

In reference to the above code, what JS code do you need to write and execute in order to:

-   GET the anchor element object?
:::info
```
el.children[1]
:::
-   READ the content of the anchor element?
  :::info
```
el.children[1].textContent
```
:::
-   Change the source of the image element to “images/unicorn.gif” ?
:::info
```javascript=
el.children[0].src = "http://images/unicorn.gif"
```
:::
-   ADD the class “important” to all elements in the `children` list?
:::info
```javascript= 
el.children[0].class="important";
el.children[1].class="important";
```
*if you typed above code will have a class called "class" instead of important. Modified version: *
```
el.children[0]['important'] = " ";
el.children[1]['important'] = " ";
```
:::
What if there were 1000 children element objects in this list?
:::info
```javascript=
let childCount=el.children.length-1
for (let i = 0; i <childCount; i++)
  el.children[i].class = "important";
```
:::
What if also, we only wanted to add the class “important” if the element is an anchor and NOT an image?
:::info
```javascript=
let childCount=el.children.length-1

function addImportant (){
  if (el.children[childCount].tagName==="A"){
    if (childCount<0){
    return []
  }else {
    return el.children[childCount].class="important"
  }
    childCount--
  }
}

//another version: 
for(let i=0;i<= el.children.length -1; i++) {
  if (el.children[i].tagName == "A" || el.children[i].tagName == "IMG"){
  }else{
     el.children[i].name = "important";
  }
}

:::



If I run some magical code that queries the page, finds, and returns to you an object that represents an element, and I give it the variable name `specialEl`… What code would you need to run in order to:

-   GET the type of element this is?
:::info
```javascript=
console.log(specialEl.nodeName)
```
:::
-   Check whether this element has an ID?
:::info
```javascript=
SpecialEl.hasOwnProperty("ID")
```
I assumed that this would given that this element is supposedly represented in the object, so presumably one should be able to figure out its actual ID (in HTML) just by checking to see if it's a category in the object 
:::
-   Change the text content of this element from “Code yuck” to “Code YES!” ?
:::info
```javascript=
let specialElText= document.getElementsByTagName([specialEl.nodeName]).innerHTML 

function changeText (){
  if (specialElText==="Code yuck"){
    return "code YES!"
  }
}
```
:::
-   To add the class “X” to this element? (It already has a class called “Z”.)?
:::info
```javascript=
let classTag = specialEl.class
classTag="Z"

function addClassTag (){
  return classTag + " X"
}
```
???


:::
-   Check whether there are any other nested elements inside this one?
:::info
```javascript
specialEl.?element1.?element2.?element2 etc. 
```

idea 2: 
```javascript=
console.log(specialEl);
```
Then you can see if `specialEl` nested any element inside. 
:::  
      
    

Try copy/pasting the prior code or constructing your own “demo” object into your console and testing out your hypotheses to these prompts.

### [ ](#Elements-have-many-many-properties… "Elements-have-many-many-properties…")Elements have many many properties…

So far we’ve been presenting you with little sketches of what element objects in the DOM look like. Example:

```
{
  tagName: "DIV",
  id: "petStore",
  className: "container",
  textContent: "Welcome!"
}

```

But this is just a few of the hundreds of properties that elements have. Most developers don’t have all of these memorized. We know a few common ones we often use (like the ones I mention) and if we want to do something to an element that our short-list doesn’t solve - we look it up.

Programmers think:

> There must be a relevant element property to do the thing I want to do.  
> I need to research what that property is and what kind of values it needs.

---

[ ](#Querying-Elements-from-the-DOM "Querying-Elements-from-the-DOM")Querying Elements from the DOM
---------------------------------------------------------------------------------------------------

So now that we have a general idea of how to manipulate objects, and we established that working with elements, the DOM, is all about reading and manipulating the property/values of objects…

> How do we actually GRAB elements from the DOM?

What we need to do is _query_ the DOM and have the comptuter fetch for us element(s) object(s) that we need.

MEMORIZE THIS PATTERN!

-   `document.querySelector("selector")`  
      
    

Where _selector_ is a **CSS selector String**.

-   Select by tag: `"someTag"`
-   Select by ids: `"#someID"`
-   Select by classes: `".someClass"`
-   Any CSS valid selector: `"div article.x > span"` _Select span elements, that are direct children to article elements with the class x, anywhere inside a div._
-   Don’t forget the double quotes around your selectors to make them interpretted as Strings (or it might protest.)

What `document.querySelector()` does is it is a function that when called accepts a pattern and looks for an element in our DOM, returning to us the element object if it finds it. Example:

```javascript
<!-- HTML -->
<div id="x" class="apple">
  <div id="y">
    <p class="story">My Paragraph</p>
  </div>
</div>

```

```javascript
// Computer conceptualizes the DOM like this:
{
  tagName: "DIV",
  id: "x",
  className: "apple",
  children: [
    {
      tagName: "DIV",
      id: "y",
      children: [
        {
          tagName: "P",
          className: "story",
          textContent: "My Paragraph"
        }
      ]
    }
  ]
}

```

```javascript
document.querySelector("#x"); // returns object representing element div#x
document.querySelector("#x").className; // returns class "apple" of div#x
document.querySelector("#x").className = "apricot"; // sets|changes class of div#x

// Using variables helps make our code readable and references reusable

let el = document.querySelector("#y"); // returns the div#y object
console.log(el.className);             // prints "" to the console
el.className = "pineapple";            // sets the class to "pineapple"

let paragraph = el.children[0];   // el was div#y, children at index 0 is p.story
alert(paragraph.textContent);     // alert popup with textContent value

```

So now we can use Javascript to query the DOM, get elements, and then change them using what we understand about object manipulation.

**Above demo code:
**
-   Create a new PEN in codepen and copy the HTML into the HTML panel.
-   Go into debug mode and try the above JS code line by line in the console.
-   Get comfortable TYPING out this level of code by memory.  
      
 

Using **[Bootstrap Meowmix](https://codepen.io/jmk2142/pen/EwKXbo)**:

-   Apply the patterns and techniques above to:
    -   Select and query elements of your choosing.
    -   Read the values of different element properties.
    -   Set or change the values of different element properties.
-   HINT: Since this is a bootstrap page - there are certain classes like the ones that end in `danger, warning, info, primary` that if you switch out… will give you an interesting effect.
-   Report your findings and thoughts.

:::info
Using debug mode to query different elements of the document is an effective way of discovering the relationship between different elements (ie what is selected when I try to change the color of the text in all ```h1``` elements?). It also allows you to change visual elements of the document using ```document.querySelector``` or  ```document.getElementByID``` and to use JS to make visual changes to the page <i>without</i> yet having to trigger everything via ```onclick``` with HTML. In this way it's a really effectiev way to see what visual changes you can trigger with JS and to learn and practice the syntax involved in calling different elements. 
:::

### [ ](#CSS-Properties "CSS-Properties")CSS Properties

If you want to dynamically apply styles the easiest way to do it is to create regular CSS rules and then use classes to toggle the styles on or off. Example:

```

<div id="item-1" class="answer">My Correct Answer</div>
<div id="item-2" class="answer">My Incorrect Answer</div>

```

```
.correct {
  color: green;
}
.incorrect {
  color: red;
}

```

```
// SETS class to answer and correct
// APPLIES the .correct CSS style rules
document.querySelector("#item-1").className = "answer correct";

// ASSIGNS variable el as reference to element object (readability)
// CONCATENATES the second class to the first with space
// APPLIES the .incorrect CSS style rules
let el = document.querySelector("#item-2");
el.className += " incorrect";

```

However you can directly manipulate an element object’s style rules using the elements `style`property.

The `style` property is an object `{ }` with many property value pairs. Every CSS rule you can make is represented in this object. Much like we have manipulated element properties, we can manipulate this CSS style object’s properties as well.

```
<div class="pet">CAT</div>

```

```
.pet {
  width: 100px;
  font-family: Helvetica;
  background-color: gold;
}

```

```
{
  tagName: "DIV",
  className: "pet",
  style: {
    width: "100px",
    fontFamily: "Helvetica",
    backgroundColor: "gold"
  }
}

```
:::info
Above Demo Code:

Compare and contrast the syntax of the CSS (rules) and how the computer represents the style object as part of the DOM.

-   What are some of the key differences between the two?
```
To seperate the property or value pairs, 
the syntax of CSS will use semicolons 
but the syntax of JS will seperate it by commas.
Also, the attribute are in spinal-case in the syntax 
of CSS, but string are in camelCase in JS.
```
-   If you wanted to change the background color to “salmon” what would you write in the console (JS code?) 
:::info
```javascript=
el.style.backgroundColor=salmon
```
:::      
    
:::info
Using **[Bootstrap Meowmix](https://codepen.io/jmk2142/pen/EwKXbo)**:

-   Using `document.querySelector()` and `console.dir()` lookup the `style` property of an element and browse through the list of properties available.
-   What are some style properties you’ve used in CSS before and can you manipulate them through JS?

```
background-color, display, border, etc.
```

-   If an element is not using a style rule, how is that represented in the object as a property/value pair?
:::info
```
Their property will have an empty string. 
property:""
```
:::
---

[ ](#Traversing-the-DOM… "Traversing-the-DOM…")Traversing the DOM…
------------------------------------------------------------------

If the DOM represents all elements as objects and they’re all nested in one giant object, what does this mean for us?

### [ ](#Tinker-Activity-Stuff3 "Tinker-Activity-Stuff3")Tinker Activity Stuff:

Let’s explore a few more _interesting_ properties that elements have.
:::info
Using **[Bootstrap Meowmix](https://codepen.io/jmk2142/pen/EwKXbo)**:

-   Using the `Element` inspector with Meowmix, use the `Copy > Copy JS Path` to grab an element and set it to a variable `el`.
-   Use `console.dir(el)` to print an element object to the console.
-   Explore the object, “opening it up” by clicking on the small triangle/caret next to it.
-   Browse/Scroll through the object to get a superficial awareness of the different properties available. Thoughts?
```
There are many property-value pairs and some common 
properties like `children` and `style`.
```
-   Dig deeper by clicking into the following properties.
    -   `children`
    -   `parentElement`
    -   `nextElementSibling`
    -   `previousElementSibling`

:::info
-   What do the values of these properties represent?
-   What is the relationship between an element and the values of these above properties?
-   How far does the rabbit hole go?

```
All the properties mentioned above are like a
family where any element nested within an
element is a child of that element. 

parentElement is the parent element of a 
particular node. It can be used as a DOM 
element object. You can follow the parent 
element all the way to the body or the header. 
You can follow the child element all the way 
to the most specific element. 
nextElementSibling property returns the element 
immediately after the specified element 
previousElementSibling returns the previous 
sibling of an element, or null if the element 
is the first in the list.
```
:::
Extend your thoughts to the following context:

```
<article id="item-xyz">
  <h3>Code is fun!</h3>
  <p class="lead">It's a challenge but...</p>
  <p>I practice every day at <a href="http://codepen.io">Codepen</a></p>
  <div>
    <span class="author">Professor JK</span>
    <span class="published">05/16/2021</span>
  </div>
</article>

```

```
// Code to articulate
let el = document.querySelector("div > span");
let name = el.textContent;
console.log(name);

let articleEl = el.parentElement.parentElement;
alert(articleEl.id);

let pargraphEl = articleEl.querySelector(".lead");
let linkEl = paragraphEl.nextElementSibling.querySelector("a");
linkEl.href = "http://codepen.io/jmk2142";

let dataEl = document.querySelector("div");
dataEl.children[0].textContent = "05/16/2022";

```

-   Take turns verbally articulating the above code line by line, expression by expression to describe the state changes, sequence of statements/routines, and causality of executing said routines.
-   Try using terms like:
    -   object, function, call, return, property, value, data, string, first/second/next/then, variable, assign, get, set, execute, console, print, index.
-   There are a few new twists here. You can make observations about the code behavior by creating a pen with the HTML and going through the JS in the console line by line.
-   What is the implication of this with respect to starting at some location within the structure of the DOM and getting to another location? In other words, “traversing the DOM”.


:::info
-- Answer: 

As mentioned previously, all the properties are like a family where any element nested within an
element is a child of that element, the parent element, and coexists with a sibling element. 

Understanding that the DOM is structured like a "family tree" and that the parent of any node is the node one level above it and closer to the document in the DOM hierarchy, and the children nodes are the nodes one level below it, helps navigate the DOM.

We can use the
<p> <i>parentNode</i> </p>
    and link parentNodes
    
<p>
</p>

    parentNode.parentNode;
  
</i>
    
</p>
to traverse upwards, and we can use
<p><i>childNode</i>
    
</p>
and all the nodes below it, such as


    childNodes
    firstChild
    lastChild
    firstElementChild
    lastElementChild

to retrieve the children nodes under the parent node.

:::
---

[ ](#Manipulating-the-Web-for-Practice "Manipulating-the-Web-for-Practice")Manipulating the Web for Practice
------------------------------------------------------------------------------------------------------------

Use **[Bootstrap Meowmix](https://codepen.io/jmk2142/pen/EwKXbo)** for the following. Or feel free to use any website (E.g. Twitter, Pinterest, Facebook, TC’s website) to hack around. Meowmix is simpler so it’ll be more clear in terms of what is what. But “hacking” a website and fabricating fake-news is a lot more fun. ![:camera_with_flash:](https://assets.hackmd.io/build/emojify.js/dist/images/basic/camera_with_flash.png)

-   Using the `Elements` inspector and `Console`, tinker around the Meowmix page and get comfortable with the Javascript we’ve been talking about above:
    -   Querying elements
    -   Reading element properties
    -   Manipulating the value of said properties
-   Report back what you set out to do as a Tinker group, how you went about it, what the results were, and what you noticed / learned as it relates to the materials covered above.
:::info
Moira: We each tackled different parts of the Tinker seperately and then we came together and workshopped each other's parts to make sure that they worked. This allowed us both to learn from each other and to correct each other. It also allowed everyone to master a slightly different skillset and be able to teach it back to other group members effectively. 

Jiayi: It provides us a chance to add/change/play around with different classes, properties and value of the properties.By practicing the tinker, we graduatly build a confidence in coding in JS and sharing out the difficulties with others provides us a good way to improve our coding skills by learning from each others. 

Estelle: The activity was a good exercise to apply the manipulation of elements and see changes in real time. By seeing how my team works and how they approach the Tinker in different ways allowed me to expand my understanding of JS concepts in a different manner than I originally approached it. 
:::
-   **EXTRA:** Explore one of your own HTML/Bootstrap project in debug mode, using the following tools. Try making manipulations through the `Elements` and `Console` tools. Using your a small project like your own will also be helpful in making connections since the classes, rules, structure are all your own - easier to understand what you’re doing.

---

[ ](#Super-Challenges "Super-Challenges")Super Challenges
---------------------------------------------------------

Technically, these are within or very close to the concepts we’ve gotten through but applied in a new (DOM and elements) contextual way so of course, it’s going to be challenging as hell. ![:see_no_evil:](https://assets.hackmd.io/build/emojify.js/dist/images/basic/see_no_evil.png) ![:hear_no_evil:](https://assets.hackmd.io/build/emojify.js/dist/images/basic/hear_no_evil.png) ![:speak_no_evil:](https://assets.hackmd.io/build/emojify.js/dist/images/basic/speak_no_evil.png)

If you can solve all these you’re ahead of the game. If you have trouble, don’t worry - there are things you can start to learn and be aware of as we keep going down this path and revist these concepts again and again.

The concept of functions are going to be an important one though as we march into the next unit - where understanding the details and nuances of functions as well as what data goes in and what data comes out… is going to be the foundation for being able to make things like button clicking interactive.

**Challenge 1:** Create a function that changes the text color to `#e91e63 ` any time the function is called.

-   Function name: something appropriate
-   Parameters: 1 String argument - a CSS Selector
-   Body: function should query the element using the argument, then change the appropriate property.
-   Returns: none
-   Other: proper indentation

:::info
Answer: 
HTML Code
```htmlembedded=
<div id="item-1" class="answer">My Correct Answer</div>
<div id="item-2" class="answer">My Incorrect Answer</div>
```
CSS: 
```
.correct{
  color: green;
}

.incorrect {
  color: #e91e63; 
}

```
JavaScript: 
```javascript=
let a = document.querySelector("#item-1");
let b = document.querySelector("#item-2");

let el = [a, b];


function colorChange() {
for(let i=0; i<= el.length -1;i++){
   if(el[i].id == "item-1"){
    el[i].className = "correct";
  }else {
    el[i].className = "incorrect";
  }
}
}
```



:::

**Challenge 2:** Create a function that can will change multiple element texts

Instead of `document.querySelector()` you will need to use `document.querySelectorAll()`

See [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll)

-   Function name: something appropriate
-   Parameters: 2 String arguments - a CSS Selector, a text message
-   Body: function should query ALL elements matching the selector you passed in as an argument. It should loop through the list of elements returned by `querySelectorAll()`and for each element object, add or change the text content to the text message passed in as the second argument.
-   Returns: none
-   Hints: arrays, loops
-   Other: proper indentation, formatting
:::info
```javascript=
function changeText(cssSelector, text) {
  let arrContentMatch = document.querySelectorAll(cssSelector);
  let contentMatchCount = arrContentMatch.length - 1;
  for (i = contentMatchCount; i >= 0; i--){
    text += "meow mix meow mix does deliver";
  }
}
```
:::

**Challenge 3**: Refactoring above function to augment its behavior. Function will alternate between adding color and changing text, as well as set an id for all elements.


Additional Function 1:

-   Function name: `colorizedEl`
-   Parameters: 1 element Object argument
-   Body: this function should change the color property of the passed in element object to `#e91e63 `.
-   Returns: the element object that you just changed the color of  
      

:::info
```javascript=
function colorizedEl(el) {
  if(element.id === "item-1")
    element.style.backgroundColor = "#green";
  else
    element.style.backgroundColor = "#e91e63";
  return element;
}
```
:::

Additional Function 2:

-   Function name: `editedEl`
-   Parameters: 2 arguments - 1 element Object argument, 1 text message
-   Body: this function should add or change the text content to the text message passed in as the second argument.
-   Returns: the element object that you just changed the text of  

:::info
```javascript=
function editedEl(element,text) {
  if(element.id === "item-1")
    element.textContent += text;
  else
    element.textContent += "change";
}
```
:::
      
    

Additional Function 3:

-   Function name: `setID`
-   Parameters: 1 element Object argument
-   Body: this function should set an id on the element passed into the function as your argument to the following pattern: `id-` + `randomNum`. E.g. `id-101`, `id-224`, `id-694`.
-   Returns: none  

:::info
```javascript=
function setID(element argument) {
   element.id = "id-" + randomNum (100,700);
 }
 ```
 :::
      
    

Refactored Function: Function from Challenge 2 but integrating the additional Function 1, 2, and 3

-   Function name: something appropriate
-   Parameters: 2 String arguments - a CSS Selector, a text message
-   Body: Using your existing function from Challenge 2 you will modify/refactor it to do the following new thing. While looping through elements you will alternate between changing the color and changing the text. If the index is even you should use `colorizedEl` to change the color of the element. If the index is odd you should use `editedEl`. All elements should be given an id using the `setID` function.
-   Returns: none
-   HINT: arrays, loops, conditionals, using the function returns in a smart way (see Additional Function 1 and 2), calling functions in functions.
-   Other: proper indentation, formatting


:::info
```javascript=
function getRandomArbitrary(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}


why this one also works? 
Math.floor(Math.random()*pics.length)
```
:::

:::success
*** We tried tackling this together for a long time but still was unable to crack it; we are still left wondering how, we may bring it to our office hour!


:::
Thing is you don’t really need me to prove your solution to these challenges do or don’t work. If you want answers, create a codepen with some demo code in the HTML and JS. Run your proposed solutions (call your functions) and see if the visual results work. ![:grin:](https://assets.hackmd.io/build/emojify.js/dist/images/basic/grin.png)
