JavaScript challenge [4]

Date:

카테고리:

태그:

JavaScript Object Browser

JavaScript Object broswer

  1. console에 Document를 입력하면 Document Object가 나온다. (HTML를 볼 수 있다)
  2. Document.title 등 HTML tag를 불러 올 수 있다.
  3. Document.title = ‘value’ 로 값을 변경할 수 있다.

즉, JS는 HTML과 연결되어있다.

JavaScript in HTML

JS는 HTML과 연결되어있다.
따라서 HTML value를 변경이 가능하다

const title = document.querySelector("#title");

title.innerText = 'value';

JavaScript Find HTML elements

const hellos = document.getElementsByClassName("hello");
//  array 반환

const title = document.getElementsByTagName("h1");
const title = document.querySelector(".hello h1");
// 하나의 element 반환

JavaScript Events는

const title = document.querySelector("#title");

title.style.color = "red"; 
// HTML의 style을 변경할 수 있다.
  1. Events JavaScript의 Events는 여러 상황을 이해한다 ```JavaScript

function handleTitleClick() { console.log(“title was clicked”); }

const title = document.querySelector(“#title”); title.addEventListener(“click”, handleTitleClick); // title이 클릭되면 handleTitleClick 함수를 실행한다.

console.dir(‘title’) // title의 모든 정보를 볼 수 있다. // 앞에 on이 붙혀있는 것들이 작동하는 Events

function handleMouseEvent(){ console.log(“mouse is here”); } title.addEventListener(“mouseenter”, handleMouseEvent); // mouse가 title 위에 있으면 handleMouseEvent 함수를 실행한다.

// Elements.addEventListener(“event”, function);

function handleMouseLeave(){ console.log(“mouse is gone”); } title.addEventListener(“mouseleave”, handleMouseLeave); // mouse가 title 위에서 벗어나면 handleMouseLeave 함수를 실행한다.


# CSS in JavaScript

CSS 변환을 JS로 해보자

```JavaScript
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
    //  with condition
    if((h1.style.color) === "blue"){
        h1.style.color = "tomato";
    } else {
        h1.style.color = "blue";
    }
}
h1.addEventListener("click", handleTitleClick);
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
    //  with condition
    const currentColor = h1.style.color;
    let newColor;
    // empty 
    if((currentColor) === "blue"){
        newColor = "tomato";
    } else {
        newColor = "blue";
    }
    h1.style.color = newColor;
}

h1.addEventListener("click", handleTitleClick);

위와 같이 변환이 가능하다.

JS 카테고리 내 다른 글 보러가기

댓글 남기기