instagram 댓글기능 구현

윤수민·2022년 10월 30일
0

클론코딩

목록 보기
1/2

#1 Westagram


weocd 과제로 나온 인스타그램 클론 코딩, 기본적인 레이아웃은 이렇다. 여러가지 기능들을 구현하던중 필수과제로 댓글기능을 구현 하여야하는데 어떻게 해야할지 몰라서 구글링을 하던중 createElementappendChild를 사용하여 기능을 구현하였다.

#2 createElement와 appendChild

createElement : HTML 문서에서, Document.createElement() 메서드는 지정한 tagName의 HTML 요소를 만들어 반환합니다. tagName을 인식할 수 없으면 HTMLUnknownElement (en-US)를 대신 반환합니다.

appendChild : 메소드는 한 노드를 특정 부모 노드의 자식 노드 리스트 중 마지막 자식으로 붙입니다. 만약 주어진 노드가 이미 문서에 존재하는 노드를 참조하고 있다면 appendChild() 메소드는 노드를 현재 위치에서 새로운 위치로 이동시킵니다. (문서에 존재하는 노드를 다른 곳으로 붙이기 전에 부모 노드로 부터 지워버릴 필요는 없습니다.)

#3 기능구현

<!--html 코드-->
  <div class="title">console_0<span>뚱이 남친짤</span></div>
      <div class="comments"><a href="#">댓글 1102개 모두 보기</a></div>
       <ul class="comment_ul_1"></ul> <!--부모요소가 되어줄 비어있는 ul태그-->
       <div class="comment_bar">
                                <img class="comment_img" src="imeages/smile.png">
        <form onsubmit="return false">
        <input class="comment_input_1" placeholder="댓글입력..." type="text">
        <button disabled class="comment_button_1" type="submit"><h1 class="posting_1">게시</h1></button>
         </form>
         </div>

우선 html코드에 댓글이 달릴위치에 비어있는 ul태그를 하나 만들어 주었다.

//javascript 코드
function runComment2() {
  const box = document.querySelector(".comment_ul") //부모 ul태그를 변수에 저장
  const userName = "yumsumin725";
  const comments = document.createElement("li") //comments 라는 li태그 요소를 생성
  comments.innerHTML = `     //comments변수에 html코드를 사용하여 댓글창의 레이아웃을 생성
  <div class="newcomment">
      <div>
          <b>${userName}</b>
          <span>${commentInput2.value}</span>
      </div>
          <button class="comment_hart_no"></button> 
      </div>
  ` 
  box.appendChild(comments); //작성한 html코드들을 방금 생성한 변수 box에 선언된 ul태그안에 자식요소로 넣어줌
}

그후, 자바스크립트에서 변수 부모 ul태그에 dom요소로 접근하여 box라는 변수에 저장해주었고, comments 라는 변수를 선언한후 createElement 메소드를사용하여 li태그로 만들어주었다.
변수commentsinnerHtml메소드를 사용하여 댓글창의 구조를 작성해준후, 변수box(부모 ul태그)appendChild 메소드를 사용하여 방금작성한 comments(자식이될 li태그)변수를 할당해주었다.

정상적으로 댓글이 올라가는걸 확인할 수 있다.

profile
안녕하세요!

0개의 댓글