티스토리 뷰
동적으로 Element 추가하고 삭제하는 방법
addElement()
Child node를 parent element에 붙여서 element를 생성하는 방식이다. Parent element를 명시하기 위해 parentId 를 사용하고, 어떤 종류의 element(p, h1, div 등...)를 만들고 싶은지는 elementTag로 명시한다.
- parentId
- elementTag
- elementId
- html
//동적으로 element document에 추가하는 법
function addElement(parentId, elementTag, elementId, html) {
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html; //새로 만든 element의 html content를 지정
p.appendChild(newElement);
}
removeElement()
삭제하고자 하는 element의 id만 있으면 된다
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
연습 예제)
var fileId=0; //새로 추가할 파일에 계속해서 다른 id를 부여하는 방법
function addFile() {
fileId++; // increment fileId to get a unique ID for the new element
var html = '<input type="file" name="uploaded_files[]" /> ' +
'<a href="" onclick="javascript:removeElement("file-" + fileId + ""); return false;">Remove</a>';
addElement('files', 'p', 'file-' + fileId, html);
}
참고 사이트: https://www.abeautifulsite.net/adding-and-removing-elements-on-the-fly-using-javascript
Adding and Removing Elements on the Fly Using JavaScript
I've done some work to try to simplify the process of adding and removing elements to a page dynamically. For basic applications, the addElement() and removeElement() functions I've written should be able to handle the job. For more complex applications, y
www.abeautifulsite.net
'JavaScript' 카테고리의 다른 글
JavaScript AJAX, XML 문서 받아오기 (0) | 2020.07.29 |
---|---|
JavaScript BOM (0) | 2020.07.29 |
JavaScript HTML DOM: Event listener (1) | 2020.07.28 |
JavaScript forms (0) | 2020.07.28 |
Javascript: function, events (0) | 2020.07.27 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- text_shadow
- 인용문 #주석
- JSP_CRUD
- STS4
- HTML #Tables
- HTML #media #video #YouTube
- jsp
- HTML #class
- annotation
- css
- box_model
- HTML_Formatting
- javascript #datatype
- html
- HTML_Forms
- links lists tables display
- HTML #CSS
- UserBean
- head #title #style
- 2020Camp
- HTML #Canvas #SVG
- HTML #Headings #Paragraph #Styles
- JSP환경구축
- fontstyle
- meta #link #script #base #HTML
- DynamicWebProject
- DB4free
- Block_element #inline_element
- HTML #id #iframe
- Mavenproject
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함