본문 바로가기
공부/javascript

2022.05.12 - javascript DOM 요소 속성 변경/추가

by 기묜몬 2022. 5. 12.

 

 

1. item의 글씨크기와 색상을 green 과 똑같이 바꿔라. (단, html / css 는 건들지말고, js로만 변경할 것)

==> js 풀이 (1)

item에 직접 색상과 크기를 적용시킴.

const itemElement = document.querySelector(".item");
document.querySelector(".item").style.color = "#55ff00";
document.querySelector(".item").style.fontSize = "100px";

==> js 풀이(2) 05.25 

document.querySelector를 빼고 스타일 적용해도 동일하게 나옴 !! (코드 줄이기)

const itemElement = document.querySelector(".item");

itemElement.style.color = "#55ff00";
itemElement.style.fontSize = "100px";

 

 

2. 왼쪽 신호등을 오른쪽과 같이 텍스트, 배경색 추가하라. 수정!!

 (단, html / css 는 건들지말고, js로만 변경할 것)

==> js 풀이

초반 풀이)

const listLight = document.getElementsByTagName("span");
listLight[0].textContent = "Stop";
listLight[1].textContent = "Pause";
listLight[2].textContent = "Go";

listLight[0].style.backgroundColor = "red";
listLight[1].style.backgroundColor = "orange";
listLight[2].style.backgroundColor = "green";

span 태그를 배열화 시킨다음 각 배열의 요소에 텍스트와 색상을 추가했다. 

const wrapperElement = document.querySelector(".lightWrapper");
const redLightElement = wrapperElement.children[0];
const orangeLightElement = wrapperElement.children[1];
const greenLightElement = wrapperElement.children[2];

redLightElement.classList.add('red');
redLightElement.innerHTML="Stop";
orangeLightElement.classList.add('orange');
orangeLightElement.innerHTML="Pause";
greenLightElement.classList.add('green');
greenLightElement.innerHTML="Go";

=> 문제를 다시보니 직접 스타일을 적용하는것이 아니고 css 클래스를 가져와서 적용하는것 같아서 수정했다!

 

3. 텍스트가 나타날 수 있도록 <p>태그 생성 후 <body> 태그의 자식으로 추가하라. (단, html / css 는 건들지말고, js로만 변경할 것)

==> js 풀이

creatElemnt("p") p태그 생성하여 pTag변수에 할당하고, textContent를 통해 텍스트를 변경함

마지막으로 body.appendChild로 body태그의 자식으로 추가함.

 

 

4. <li>태그를 생성하여 화면에 second가 나타날 수 있도록 <ul>태그의 자식으로 추가하라. (단, html / css 는 건들지말고, js로만 변경할 것)

==> js 풀이 

liTag 변수 선언하고 createElement("li") li태그 생성 후 textContent로 텍스트를 변경함.

그 후 liTag를 ulElement의 자식으로 추가함.

const ulElement = document.querySelector("ul");

const liTag = document.createElement("li");
liTag.textContent = "second";
ulElement.appendChild(liTag);

5.  투두리스트에 list태그를 추가하고 값을 넣어라.

==> js 풀이

1. for 문을 돌려 4개까지 리스트를 생성하고

2. li 태그 생성을 위해 listTag 변수 선언 

3. ulElement에 listTag 변수를 자식으로 추가하고

4. task[i]배열의 값을 listTag.textContent를 사용하여 값을 넣어줬다. 

const task = ["Code", "Run", "Eat", "Sleep"];
const ulElement = document.querySelector("ul");

for(let i=0; i<4; i++){
  const listTag = document.createElement("li");
  ulElement.appendChild(listTag);
  listTag.textContent = task[i];

}