Blog Day 20: Accessing HTML using DOM

Inseo Park·2021년 7월 27일
0

Path to Data Scientist

목록 보기
19/58
post-thumbnail

1. TIL (Today I Learned)

Accessing HTML using DOM

Achievement Goals

  1. Use Javascript with DOM to CREATE, READ, UPDATE, & DELETE HTML.
    • CreateElement - CREATE
    • querySelector, querySelectorAll - READ
    • textContent, id, ClassList, setAttribute - UPDATE
    • textContent, id, innerHTML = "" , textContent = "" - DELETE
    • appendChild - APPEND
    • Difference between innerHTML & textContent

1. CREATE - createElement

	document.createElement('div') // <div></div>
    

To use JS to control DOM
Assign a variable

	const tweetDiv = document.createElement('div')
    	// assign a variable to a code
    

It is obvious that nothing happened because tweetDiv is currently connected to nothing in the tree structure.

To include into DOM structure or HTML we have to APPEND

2. APPEND - append, appendChild

	document.body.append(tweetDiv)
    

We will use the method APPEND to put tweetDiv into the body.
However, after the append is used, still nothing is returned
This changes when information is added into the created element.

By console.log it is possible to check that tweetDiv is created in the body section of HTML

Questions:

  1. How can you put information in the element?
  • Use the method called textContent
  1. Like other tweets, how to put tweetDiv into the #container.
  • In order to include tweetDiv in the container, you have to find the container. How? Search through the DOM tree to find it.
    A easier way:

    	container.appendChild(tweetDiv);
      // this is a method used to move element into another element
      // to UNDO repeat APPEND method
      	document.body.append(tweetDiv);
          // this sends the element back into the preferred location
          

3. READ

Ways we can approach the values inside different types of variables

Primitive types = variable name;
Array = index;
Object = key;
DOM = selector (tag : ("div"), id (#tweetlist), class (.tweet)

querySelector

  • means to search for a selector
  • query means to question
  • run a query is a jargon used among programmers
const oneTweet = document.querySelector('.tweet')
// This will search for the first element under #tweet

There are many elements under #tweet but in the variable oneTweet, only one element is stored.
To call for all elements we have to use querySelectorAll.
When using querySelectorAll, we can use the elements like an Array, which is not an Array but an Array-like Object.

const tweets = document.querySelectorAll

Some old-school ways to lookup for elements

const getOneTweet = document.getElementById('container')
const queryOneTweet = document.querySelector('#container')
console.log(getOneTweet === queryOneTweet) // true

We created the div element as is ready to be included in our wished lookup place. Below code will include the created code into our place we wish.

 const container = document.querySelector('#container');
 const tweetDiv = document.createElement ('div');
 container.append(tweetDiv);
 

The added element tweetDiv is not given a class name which makes it not connected with the CSS file.

Further Study

  1. What happens if you put 'div' as the first index of the querySelector
  • returns the first div or null when there is nothing
  1. Is it possible for querySelector to do more complicated tasks.

    const el = document.querySelector("div.user-panel.main input[name='login']");
    // querySelector can go more complicated and search for complicated stuffs
  2. Does querySelector's parent always has to be document?

  • Any object with a children element and is under document can be put in the parent of querySelector.

UPDATE - textContent, classList.add

To add a text content in the created div or element

console.log(oneDiv) // <div></div>
oneDiv.textContent = 'dev'
console.log(oneDiv) // <div>dev</div>

To add creadted element into a class list

oneDiv.classList.add('tweet')
console.log(oneDiv) // <div class="tweet">dev</div>

To add new element to the #container

const contianer = document.querySelector('#container')
container.append(OneDiv);

Question

  1. Can we add the element into an attribute aside from class or id?

    use Element.setAttribute()
    // set the value of an attribute on the specified element
    
    <button>Hello World</button>
    const b = document.querySelector("button")
    b.setAttribute("name", "helloButton");
    b.setAttribute("disabled", " ");
  2. To include CSS in a browser

    in the <head>
    <link rel="stylesheet" href="Style.css"/>
    </head>

Element.getAttribute()

// this gets the value of a specified element //
    <div id="div1">Hi Champ!</div>
    const exampleAttr = div1.getAttribute('id');
    // --> "div1"

Element.removeAttribute()

// Given: <div id = "div1" align = "left" width = "200px">
document.getElementById("div1").removeAttribute("align");
// Now: <div id = "div1" width = "200px">

DELETE - remove, removeChild

a. condition - you know the element's location

const container = document.querySelector('#container')
const tweetDiv = document.createElement('div')
container.append(tweetDiv)
tweetDiv.remove() // this deletes the appended element.

b. to delete multiple elements use "innerHTML"

document.querySelector('#container').innerHTML = '';
** This has security reasons, use Node.textContent instead

c. use (for, while, etc) to rename child elements

const container = document.querySelector('#container')
while(container.firstChild) {
  container.removeChild(container.firstChild);
  }

d. to not delete the H2 "Tweet List"
leave one element behind in using while

const container = document.querySelector('#container')

while (container.children.length > 1) {
  container.removeChild(container.lastChild);
  }
  

e. Only delete the elements with .tweet

const tweets = document.querySelectorAll('tweet');
tweets.forEach(function(tweet) {
  tweet.remove();
  })
   OR
 for (let tweet of tweets) {
   tweet.remove()
   }

Further Study

  1. Difference between element & node in javascript DOM
  • Element inherits from Node, in the same way that Dog inherits from Animal. ELement is a type of node.
  1. Difference between children and childNodes in javascript DOM
  • Children is a proeprty of element which returns the child element of an element as objects.
    The childNodes property is a property of Node in Javascript and is used to return a Nodelist of child nodes,
    The difference is that children work upon elements and childNodes on differne kind of nodes
  1. Difference between remove & removeChild
  • remove only needs a refernce to the child, removeChild needs both the parent and the child. The return result is same.
  1. Why array method does not work for nodelist.
  • because nodelist is not an Array, it is a Array-like object.
  1. How to convert nodelist into Javascript array
  • Use Array.from() method, this is a static method that creates a new, shallow copied Array.

2. 3 Things to be Thankful for

  1. Thankful for the great study I had.
  2. Thankful for having good people to talk to.
  3. Thankful for keeping my brother safe and me happy.

3. Ideas and Things to think about

  1. A good planner is something planned before but I decided to add on to my planner when I finish some things or daily routines. This is because when my pre-planned roles are not accomplished I kind of get frustrated and down. Therefore I decided to focus on things I can do better not things that I failed to do.
profile
my journey to become a data scientist.

0개의 댓글