# Intro DOM(Document Object Model)
- The DOM is a javascript representation of a webpage.
- It's your JS 'window' into the contents of a webpage.
- It's just a bunch of objects that you can interact with via JS.
#Document Object
- The way works is when browsers load webpages and part of HTML and CSS and then creating Javascript object based on elements and those styles.
- They has a relationship that all JS, HTML and CSS is connected. It is tree structure and the most important and on very top of this structure is called DOCUMENT.
- The document object is our entry point into the world of the DOM. It contains representations of all the content on a page, plus tons of useful methods and properties.
- It is automatically made by browser, and whenever you open new browser, it makes new DOM. It is like a bunch of represent of contents on webpage. It is root of tree of computer science.
- You can see the whole document object on develope console log, and you can change HTML elements with it by not touching HTML elements. You can manipulate all elements with DOM.
# getElementById
- You can select elements and manipulate them with getElementById. It is the method existed on the document.
- When you call it, we pass in a string and this string nees to correspond to some ID on an element. So if there is an element found with that Id, it will be returned and if it can't be found, then we get null.
- When we select something, what we are doing is we are telling JS that please fatch me the objevt that represents some element on the page matching some ID.
- We are not actually selecting HTML or CSS, but we are selecting DOM object.
#getElementsByTagName & ClassName
- getElementsByTagName and getElementsByClassName have to choose more than one. Get all of the same name tags or class.
- Let's say you choose 'img' tag with getElementsByTagName, all of img tag would be chosen and it returns an HTML collections.
document.getElementByTagName('img')
//You can get something looking like array but it is not. You can see all img tags
const allImgages = document.getElementsByTagName('img')
allImages // HTMLCollections(4) ...
allImages[0] // you can get the first image
- This HTML collection is not an array, so you cannot access somethin like map . ex> allImages.map // undefined
- You can do have length like 'allImage.length' // 4 and see index. Also you can use 'for...of 'loop. It is iterable collection but not an array.
- Each image has a source and you can do console.log to see the source. You can change all the images with for...of loop.
for(let img of allImages){
console.log(img.src)
}
- You can also change all the image source. Then all images will be changed into the same images.
for(let img of allImages){
img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e2/Silky_bantam.jpg/440px-Silky_bantam.jpg'
}
- What this collection returns? What's in HTML collection and what is Element?
- Element is an object in JS that will getting back that has all the properties and represent single HTML element. The actually name the type of this object is Element with capital E.
- getElementByClassName is collected by className. If you don't have any class name and then you will get null like empty HTML collection[]
#querySelector
- A newer, all-in-one method to select a single element. You can use one method to select id,class, element, attribute or css whatever you want.
- querySelector just gives us the first match.
document.querySelector('p') // tag
document.querySelector('#banner') //id
document.querySelector('.square') // classname
// you get only the first one when you use tag and classname.
- You can also select second one with nth-of-type
document.querySelector('img :nth-of-type(2)') // you get the second image
- Also can find specific one
document.querySelector('a[title = "JAVA"]')
- querySelectorAll is exactyl the same principle but it returns all matched element instead of only first one.
- You can get all tags nested inisde of parent tag
document.querySelectorAll('p a') // you can find anchor tag in p
#innterHTML, textContent, innerText
- These one is using for manifulaton.
- innerText returns all text contents contained by an element and all its child element.
document.querySelector('p').innerText // 첫번째 p의 내용을 리턴함
- You can also change the contents with this
document.querySelector('p').innerText = 'lolololol' // change it into 'lolololol'
- textContent gets the conentes of all elements, including <script> and <style> elements. (innderText only shows human-readable elements.) When you use textContent, you can see some spaces between senteneces because it is made from markup tags.
- Both of them can change contents.
const allLinks = document.querySelector('a');
for(let link of allLinks){
link.innderText = 'I am a Link!!'
}
// it will change all of a tags into 'I am a LINK!!'
- innerHTML gives us the entire of makeups contained some of the elements.
- We don't really use this on HTMl because you ususally want to see markups when you need to update contents or change innerHTML.
- innerHTML treats tags as HTML. Browser and DOM recognize it is update and set up HTML.
document.querySelector('h1').innderText = '<i>askdjas</i>' // <i>askdjas</i>가 그대로 보여짐
document.querySelelctor('h1').innerHTML = '<i>askdjas</i>' // 이탈릭체로 바뀐 askdjas가 나옴.
- The three of them can update contentx but only innerHTML can add elements inside of other elements.
- You can also use += when you update HTML
document.querySelector('h1').innderTHML += '<sub>asjdsa</sup>'
# Attributes
- Elements have lots of different attributes involved like href of anchor tag, source of img but also Id, class are considered as an attributes.
- id attribute changes its id name. In this case, CSS properties is removed because the css design doesn't belong to the previous id name. So it is just removed
document.querySelector('#banner').id = 'whoopp' // id is changed into whoopp
- Also can change image source with src and access with this
document.querySelector('#banner').src
document.querySelector('a').href
document.querySelctor('a').title
//You can access these properties
- There is another way to access attributes with getAttribute / setAttribute
- getAttribute() is getting it directly from HTML itself.
firstLink.getAttribute('href') // /wiki/list_of_chicken_breeds
- You can change attributes with setAttribute()
firstLink.setAttribute('href','http://www.google.com')
// first arugment is what you want to pick and the second one is what you want to change to
const input = document.querySelector('input[type='text']')
input.type // text
input.type = 'password' // chagned text into password
input.setAttribute('type','text') // back to text input
# Manipulate style
- Select something and change thier css style.
- Such as h1.style // you can see many css properties, and the big difference with css is that all of properties are showed camelCase. like in css, fond-size has hyphen but in DOM, it is written by camelCase.
- This DOM object doesn't show current css style unless you set up the style sheet.
h1.style.color // 'magenta'
h1.style.color = 'green'
- You can set up diverse styles through DOM
- If you do change one thing, it is easy to do, but If you have many things to chage , and it will be annoying to do . What's more is that making of a bunch of inline styles change is not ideal. inlign style is very specific, so we should avoid to use inline.
- The better way to do is useing class.
const allLinks = document.querySelectorAll('a');
for(let links of allLinks){
link.style.color = 'rgb(0, 108,134)';
link.style.textDecorationColor = 'magenta';
link.style.textDecorationStyle = 'wavy';
}
- When you write code like this, it works but still not really good because all of them is inline style markups.
- And the other issue here is that if you didn't write inline style, you cannot see the styles in the first place. You cannnot tell what font size is in h1. You need to figure out css sheet first.
- There's another way fo getting the actual computed style once everything's been applied. 실제로 계산이 되어있는 스타일을 가져올 수 있게 된다.
- It might have multiple style sheet and it might have complicted styles and there's the whole cascade to consider and specificity. so, at the end of the day, certain styles mighe be applied and then overwritten and then over written.
- So it really we have to wait until things are loaded and everything has been computed by the browser to figure out actual styles.
windoew.getComputedStyle(h1) // it will show ordered css style declations
- it will access to css style. It is not common way but you can get any css styles .
window.getComputedStyle(h1).color
window.getComputedStyle(h1).fontSize // 32px
# classList
- When you have lots of styles to change it, it is better to use css class than inline style and apply that class
- In particular when you have some event that click something and is applied some effect, JS is used to do that.
- To manipulate some class, you need to choose it first.
const h2 = document.querySelector('h2')
h2.getAttribute('class') // you can find class in h2
h2.setATtribute('class','purple') // h2 has class named purple now.
- If you want to add one more class named 'border', it is going to change purple to border. just covered up.
- You can use classList to add more than one class for properties.
h2.classList // DOMTkenLIst
h2.classList.add('purple')
h2.classList.add('border') // now h2 has purple and border classes together
- When you use classList, no need to care what class was in in advance, but just add up new class.
- Common way is that toggle your class between being on and off.
- It is commonly used for todoList, accordion button and hide and show some contents etc.
h2.classList.remove('border')
h2.classList.toggle('border') // on and off
# 계층이동
- previousSibling, nextSibling, children, parentElement // They are relatively self-explanatory. All of these properties allow us to navigate or traverse or move form one element to some relative to its parent or to its parent parent.
const firstBold = docuement.querySelector('b')
firstBold // <b>silkie</b>
firstBold.parentElement // <p>..</p>
firstBold.parentElement.parentElement // <body>...</body>
firstBold.parentElement.parentElement.parentElement // <html>
- This is parent element that we can traverse upwards. We can do things to remove or insert new element or if users might click something , we can enact some change on the parent element or on a child element.
- We can also drill down to children elements. every child element has only one direct parent element , but we can have multiple children. Child element is not a single property.
- childElementCount lets you know how many child elements there are.
const paragraph = firstBold.parentElement
paragraph.childElementCount //8
paragraph.children // HTMLCollection(8)[b,b,a,a,a,a,a]
- When you see children element, you can get HTML Collection which is not array but looks like an array. It contains all children tags that are founded in order on DOM. Keep in mind that you can have multiple children elements.
paragraph.children[0] // <b>Silkie</b>
paragraph.children[0].parentElement // <p>...</p>
- If you wanto do somthig on every child element, you can iterate over children element list.
- Sibling elements allows to navigate from one element to jason sibling.
- nextSibling and previousSibling has no elements. They are giving us corresponding node.
- Some browsers make white spaces automatically and make new line into text node. It is DOM node.
const squareImg = document.querySelector('.square')
squareImg.nextSibling // #text -> this is node
- nextElementSibling / previouseElementSibling show us next or previous element.
- You can use these ones to navigate to next or previouse elements and be able to ignore some space or text node.
#Append & AppendChild
- Creaing new elements from scratch and appending it to the page or prepending it, removing elements.
- document.createElement can make new tpye of element we want to create.
document.createElement('img')
- of course the page would be not made right away when you create new img element. First of all, you don't have any source yet. Second of all, you have to tell them where to go, so it will just make an empty image.
- You need to add img source and need to append this image.
- appendchild // append it to where you want to.
const newImg = document.creatElement('img')
newImg.src = 'https://images.unsplash.com/photo-1669555514519-261ee068c278?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80'
document.body.appendchild(newImg) //add new image into body. it will be the last child of the body
newImg.classList.add('square') // to set up the same css style, added square class that is the same as other images
- Let's make new h3 element at the end of the body. It doesn't have any text in it, so you can add it with innerText and then append in the body.
const newH3 = document.creatElement('h3')
newH3 // <h3></h3> It has no text in it.
newH3.innerText = 'I am new!'
document.body.appenedChild(newH3) // <h3>I am new!</h3>
- There's another option to append is using append method. It is newer method, so it doesn't work on Internet Explorer. It is more flexible.
- let us to add more than one things, so can make two nodes or five elements to insert.
- you cannot add some string with appendChild but it works with append.
const p = document.querySelector('p');
p.append('I am new text yaaaayy!!!') //undefined //added
p.appendChild('I am new text yaaaayy!!!') // you cannot add string with appendChild
- We can also prepend with prepend method.
const newB = document.creatElement('b')
newB.append('HI!!')
newB // HI!!
p.prepend(newB) // it will be added on the beginning of p
- When you want to insert adjacent sibiling, like you want to add somthing between h2 and image, you can use inserAdjacentElement().
- You have to specify to insert it before some element or after some element. it is generic element.
- afterbegin / afterend / beforebegin / beforeend // you can set up positions with these words.
- element.insertAdjacentElement(position, element)
const h2 = docuement.createElement('h2')
h2.append('Are adorable chickens')
h2 // <h2>Are adorable chickens</h2>
const h1 = document.createElement(h1)
h1.insertAdjacentElement('afterend',h2) // h2 is made after h1.
#removeChild & remove
- removeChild is more annoying to use because it doens't remove the element we selected , but remove it from child element.
- When you want to delete an image, you need to select parents element like <body> and then call removeChild and pass in the image.
- Let's say you want to delete one <li> which is nested in <ul>
const firstLi = document.querySelector('li')
firstLi // <li class = 'toclevel-1 to...'>...</li>
const ul = firstLi.parentElement // you need to get parent element of what you want to remove 's
ul // <ul>..</ul>
ul.removeChild(firstLi) // firstLi is ul's child element. and it is deleted
- If you want to remove the first bold element,
const b = document.querySelector('b');
b.parentElement.removeChild(b)
- after this way, we have remove(). You don't need to care about child or parent elements.
const img = document.querySelector('img')
img.remove() // removed
'Udemy - The web developer camp' 카테고리의 다른 글
Asynchronous JavaScript (0) | 2022.12.10 |
---|---|
JavaScript DOM event (0) | 2022.12.01 |
JavaScript new syntax (0) | 2022.11.12 |
JavaScript Callback and Array Methods (0) | 2022.10.25 |
JavaScript function level up (0) | 2022.10.13 |
댓글