문서객체의 Style속성을 사용하면 해당 문서객체의 스타일을 변경할 수 있다.
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script>
window.onload = function () {
var header = document.getElementById('header');
header.style.border = '2px solid black';
header.style.color = 'orange';
header.style.fontFamily = 'helvetica';
};
</script>
</head>
<body>
<h1 id="header">Header</h1>
</body>
</html>
코드에서 보는바와 같이 header 문서객체에 .마침표를 통해style속성에 접근 후 다시 .마침표를 통해 변경할 css속성을 입력하여 변경할 값을 입력한다.
이때 주의할 점은 스타일시트에서 사용하던 스타일 속성 이름을 그대로 입력하면 안된다.
background-color 의 형태와 같이 특수기호 " - " 는 자바스크립트에서 식별자로 사용할 수 없으므로 다음과같이 입력하면 에러를 출력한다
header.style.background-color = 'red';
따라서 " - " 로 연결된 속성은 다음과같이 특수기호에 의해 끊겨진 단어를 기준으로 이어오는 단어의 첫글자를 대문자로 작성한다.
header.style.backgroundColor = 'red';
background-image → backgroundImage
background-color → backgroundColor
box-sizing → boxSizing
list-style → listStyle
문서 객체 제거
removeChild( )
parentNode 속성
+) appendChild( )
+) childNode 속성
문서객체를 제거할 때는 removeChild(child) 메서드를 사용하여 제거한다.
문서객체의 자식 노드를 제거한다.
<body>
<h1 id="will-remove">Header</h1>
</body>
window.onload = function () {
var willRemove = document.getElementById('will-remove');
document.body.removeChild(willRemove);
}
body문서 객체 바로 아래에 h1문서객체가 존재하기 때문에 가능하다.
일반적으로 문서 객체를 제거할 때는 parentNode라는 속성을 통해 제거한다.
willRemove.parentNode.removeChild('willRemove');
코드를 보면 willRemove 객체 - h1태그의 parentNode 부모노드인 body 문서객체를 가리킨다.
부모노드인 body태그로부터 자식노드인 willRemove 객체를 제거하는 방식이다.
여기서 추가로 한가지를 유추해보면 이전에 다뤘던 포스팅에서 appendChild( ) 라는 메서드를 사용하여 노드를 추가하고 연결하였었다.
appendChild( ) 또한 부모와 자식관계를 갖게되므로 요소노드와 요소노드, 요소노드와 텍스트노드가 연결되어있는 형태는 모두 부모와 자식관계임을 알수있다.
'JavaScript > DOM & Event' 카테고리의 다른 글
이벤트 - DOM Level 0 : 인라인 이벤트 모델 (디폴트 이벤트 - 유효성 검사) (0) | 2022.01.20 |
---|---|
이벤트 - DOM Level 0 : 고전 이벤트 모델 (0) | 2022.01.20 |
문서객체 가져오기 getElementBy (Id, Name,TagName, class) / querySelector (0) | 2022.01.19 |
문서 객체 만들기 (DOM) createElement , createTextNode , appendChild, setAttribute , getAttribute , innerHTML, textContent속성 (0) | 2022.01.18 |
문서객체 DOM (Document Object Model) (0) | 2022.01.18 |