김민태 [프론트엔드 아카데미] 3 - (4)

이동주·2021년 10월 12일
0

문자열을 활용한 HTML 다루기

DOM API의 문제점

코드만 보았을 때 구조를 명확하게 알 수 없음
=> 복잡한 UI의 마크업이 완성된 구조를 파악하는 것은 더욱 힘듬

개선방안

DOM API 제거하기

  • 문자열만 가지고 UI를 만드는 방법 사용
    : .innerHTML 사용
const div = document.createElement('div');

    div.innerHTML = `
        <li>
            <a href = "#${newsFead[i].id}>
            ${newsFead[i].title} (${newsFead[i].comments_count})
            </a>
        </li>
    `;

   ul.appendChild(div.firstElementChild);

중복 코드 제거하기

함수를 지정해서 중복 코드 제거하기

function getData(url) {
    ajax.open('GET', url, false) // true: 비동기 처리 false: 동기 처리
    ajax.send();

    return JSON.parse(ajax.response);
}

Result

const container = document.getElementById('root');
const ajax = new XMLHttpRequest();
const contents = document.createElement('div');
const NEWS_URL = 'https://api.hnpwa.com/v0/news/1.json';
const CONTENTS_URL = 'http://api.hnpwa.com/v0/item/@id.json';

function getData(url) {
    ajax.open('GET', url, false) // true: 비동기 처리 false: 동기 처리
    ajax.send();

    return JSON.parse(ajax.response);
}

const newsFead = getData(NEWS_URL);
const ul = document.createElement('ul');

window.addEventListener('hashchange', function () {
    const id = location.hash.substr(1);

    const newsContent = getData(CONTENTS_URL.replace('@id', id));
    const title = document.createElement('h1');

    title.innerHTML = newsContent.title;

    contents.appendChild(title);
});

for (let i = 0; i < 10; i++) {
    const div = document.createElement('div');

    div.innerHTML = `
        <li>
            <a href = "#${newsFead[i].id}">
            ${newsFead[i].title} (${newsFead[i].comments_count})
            </a>
        </li>
    `;

    ul.appendChild(div.firstElementChild);
}

container.appendChild(ul);
container.appendChild(contents);
profile
안녕하세요 이동주입니다

0개의 댓글