Frontend
Javascript로 외부 html 가공하기(feat. DOMParser)
wrallee
2020. 3. 29. 11:37
소스: https://github.com/wrallee/onnuri-finder
조악한 지식인 것 같지만 역시 나같은 사람들이 있을까봐 정리해본다.
상품권 가맹점을 찾기 위해 모 사이트에 들어갔는데 모바일 페이지가 없었다.
그래서 간단하게 UI만으로 구성 된 html 파일 페이지로 만들어 보기로 했다.
원본 사이트 | html 파일 사이트 |
준비물: jQuery, Ajax
$.ajax({
url: http://주소.com/abcdefg.do,
dataType: 'html',
data: {
data1 : 'mydata1',
data2 : 'mydata2'
},
success: function(html) {
var htmlDom = new DOMParser().parseFromString(html, 'text/html');
var tableDom = htmlDom.documentElement
.querySelector('table tr:nth-child(4) td table tbody')
.rows;
var rowElement = $('#resultTableBody tr:first-child');
for (var i = 0; i < tableDom.length; i++) {
var tableRow = tableDom.item(i);
rowElement.children(':nth-child(1)').text(tableRow.cells.item(2).innerText);
rowElement.children(':nth-child(2)').text(tableRow.cells.item(6).innerText);
rowElement.children(':nth-child(3)').text(tableRow.cells.item(1).innerText);
rowElement.children(':nth-child(4)').text(tableRow.cells.item(3).innerText);
rowElement = rowElement.next();
}
}
});
위 소스의 프로세스는 아래와 같이 진행된다.
Ajax 비동기 호출 → String to DOM 변환(Parsing) → html 재 구성
주요 내용은 크게 3가지이다.
1. Ajax 호출
필요한 웹사이트 화면을 String으로 받아온다.
2. DOMParser().parseFromString(...)
받아 온 String 데이터를 html(Document) 타입으로 변환해준다.
3. Document.querySelector(...)
Document 타입의 경우 querySelector 메소드를 통해 내부 요소를 골라낼 수 있다.
선택자를 사용하여 필요한 태그만 골라낸다.
4. DOM Table Object
DOM Object는 많은 필드/메소드를 제공하는데, w3school JS Reference 항목에 아주아주 방대하게 기록되어 있다.
구글에 "XXX Object w3school" 와 같은 키워드로 검색하면 쉽게 활용할 수 있다.
이후 원하는 형태로 화면을 재구성하면 된다.