728x90
반응형
728x90
반응형

Element 객체

Element 객체는 엘리먼트를 추상화한 객체

DOM은 마크업언어를 제어하기 위한 표준

 


 -식별자 API

<script>

console.log(document.getElementById('active').tagName)// LI
 var active = document.getElementById('active');
console.log(active.id); // active
var active = document.getElementById('active');
// class 값을 변경할 때는 프로퍼티의 이름으로 className을 사용
active.className = "important current";
console.log(active.className); // important current
active.className += " readed" // 클래스를 추가할 때는 아래와 같이 문자열의 더한다.
var active = document.getElementById(‘active’);
for(var i=0; i<active.classList.length; i++){
        console.log(i, active.classList[i]);
}
active.classList.add('marked'); // 추가
active.classList.remove('important'); // 제거
active.classList.toggle('current'); // 토글
</script>


 -조회 API

  <script>

    var list = document.getElementsByClassName('marked');

    console.group('document');

    for(var i=0; i<list.length; i++){

        console.log(list[i].textContent); // html, dom, bom

    }

    console.groupEnd();

    

    console.group('active');

    var active = document.getElementById('active');    

    var list = active.getElementsByClassName('marked');

    for(var i=0; i<list.length; i++){

        console.log(list[i].textContent); // dom, bom

    }

    console.groupEnd();

</script>

  

 -속성 API

<a id="target" href="http://opentutorials.org">opentutorials</a>

<script>

var t = document.getElementById('target');

console.log(t.setAttribute(‘href’, ‘http://opentutorials.org/course/1’);

console.log(t.getAttribute('href')); //http://opentutorials.org

t.setAttribute('title', 'opentutorials.org'); // title 속성의 값을 설정한다.

console.log(t.hasAttribute('title')); // true, title 속성의 존재여부를 확인한다.

t.removeAttribute('title'); // title 속성을 제거한다.

console.log(t.hasAttribute('title')); // false, title 속성의 존재여부를 확인한다.

</script>

속성과 프로퍼티

<p id="target">

    Hello world

</p>

<script>

    var target = document.getElementById('target');  

    target.setAttribute('class', 'important');  // attribute 방식

    target.className = 'important'; //// property 방식

</script>

속성과 프로퍼티 둘의 차이점

<a id="target" href="./demo1.html">ot</a>

<script>

//현재 웹페이지가 http://localhost/webjs/Element/attribute_api/demo3.html 일 때

var target = document.getElementById('target');

console.log('target.href', target.href); // http://localhost/webjs/Element/attribute_api/demo1.html

console.log('target.getAttribute("href")', target.getAttribute("href")); // ./demo1.html

</script>

 -jQuery 속성 제어 API

<a id="target" href="http://opentutorials.org">opentutorials</a>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

var t = $('#target');

console.log(t.attr('href')); //http://opentutorials.org

t.attr('title', 'opentutorials.org'); // title 속성의 값을 설정한다.

t.removeAttr('title'); // title 속성을 제거한다.

</script>

jquery에서 attribute property

<a id="t1" href="./demo.html">opentutorials</a>

<input id="t2" type="checkbox" checked="checked" />

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

// 현재 문서의 URL이 아래와 같다고 했을 때,

// http://localhost/jQuery_attribute_api/demo2.html

var t1 = $('#t1');

console.log(t1.attr('href')); // ./demo.html

console.log(t1.prop('href')); // http://localhost/jQuery_attribute_api/demo.html

 

var t2 = $('#t2');

console.log(t2.attr('checked')); // checked

console.log(t2.prop('checked')); // true

</script>

Attr attribute, prop property 방식

 -jQuery 조회 범위 제한

<ul>

    <li class="marked">html</li>

    <li>css</li>

    <li id="active">JavaScript

        <ul>

            <li>JavaScript Core</li>

            <li class="marked">DOM</li>

            <li class="marked">BOM</li>

        </ul>

    </li>

</ul>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    //$( ".marked", "#active").css( "background-color", "red" );

    //$( "#active .marked").css( "background-color", "red" );

    $( "#active").find('.marked').css( "background-color", "red" );

</script>

find를 너무 복잡하게 사용하면 코드를 유지보수하기 어렵습니다.

Node객체

시조는 최상위의 조상을 의미

node객체는 최상위 객체를 의미, 모든 객체는 node객체를 상속받음

 -Node 관계 API

 

<body id="start">

<ul>

    <li><a href="./532">html</a></li>

    <li><a href="./533">css</a></li>

    <li><a href="./534">JavaScript</a>

        <ul>

            <li><a href="./535">JavaScript Core</a></li>

            <li><a href="./536">DOM</a></li>

            <li><a href="./537">BOM</a></li>

        </ul>

    </li>

</ul>

<script>

var s = document.getElementById('start');

console.log(1, s.firstChild); // #text

var ul = s.firstChild.nextSibling

console.log(2, ul); // ul

console.log(3, ul.nextSibling); // #text, 다음 형제 노드

console.log(4, ul.nextSibling.nextSibling); // script

console.log(5, ul.childNodes); //text, li, text, li, text, li, text

console.log(6, ul.childNodes[1]); // li(html), 자식노드들을 유사배열에 담아서 리턴

console.log(7, ul.parentNode); // body

</script>

</body>

 -노드 종류 API

Node.nodeType // node의 타입을 의미

Node.nodeName // node의 이름 (태그명을 의미)

재귀함수 : 함수가 지가 자신을 호출하는 것

<!DOCTYPE html>

<html>

<body id="start">

<ul>

    <li><a href="./532">html</a></li>

    <li><a href="./533">css</a></li>

    <li><a href="./534">JavaScript</a>

        <ul>

            <li><a href="./535">JavaScript Core</a></li>

            <li><a href="./536">DOM</a></li>

            <li><a href="./537">BOM</a></li>

        </ul>

    </li>

</ul>

<script>

function traverse(target, callback){

    if(target.nodeType === 1){ // 1==Node.ELEMENT_NODE

        //if(target.nodeName === 'A')

        callback(target);

        var c = target.childNodes; // 자식 노드들을 유사배열에 담아서 리턴

        for(var i=0; i<c.length; i++){

            traverse(c[i], callback);      

        }  

    }

}

traverse(document.getElementById('start'), function(elem){

    console.log(elem);

});

</script>

</body>

</html>

 -노드 변경 API

   

appendChild(child) // 노드의 마지막 자식으로 주어진 엘리먼트 추가

insertBefore(newElement, referenceElement) // appendChild와 동작방법은 같으나 두번째 인자로 엘리먼트를 전달 했을 때 이것 앞에 엘리먼트가 추가

removeChild(child) // 노드 제거

replaceChild(newChild, oldChild) // 노드 바꾸기

 -jQuery 노드 변경 API

.jQuery에서 노드를 제어하는 기능은 주로 Manipulation 카테고리에 속해 있음

<div class="target">

    content1

</div>

<div class="target">

    content2

</div>

 

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    $('.target').before('<div>before</div>');

    $('.target').after('<div>after</div>');

    $('.target').prepend('<div>prepend</div>'); // 이전 추가

    $('.target').append('<div>append</div>'); // 이후 추가

</script>

remove는 선택된 엘리먼트를 제거하는 것이고 empty는 선택된 엘리먼트의 텍스트 노드를 제거하는 것

<div class="target" id="target1">

    target 1

</div>

<div class="target" id="target2">

    target 2

</div>

 

<input type="button" value="remove target 1" id="btn1" />

<input type="button" value="empty target 2" id="btn2" />

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    $('#btn1').click(function(){

        $('#target1').remove();

    })

    $('#btn2').click(function(){

        $('#target2').empty();

    })

</script>

교체

 

클론

이동

 -문자열 노드 제어

   innerHTML : 문자열로 자식 노드를 만들 수 있는 기능을 제공

   outerHTML : 선택한 엘리먼트를 포함해서 처리

   innerTEXT, innerTEXT : innerHtml, outerHTML과 다르게 이 API들은 값을 읽을 때는 HTML 코드를 제외한 문자열을 리턴하고, 값을 변경할 때는 HTML의 코드를 그대로 추가

   insertAdjacentHTML : 좀 더 정교하게 문자열을 이용해서 노드를 변경하고 싶을 때 사용

   

 



출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

DOM

Document Object Model로 웹 페이지를 자바스크립트로 제어하기 위한 객체 모델을 의미합니다. Window 객체의 document 프로퍼티를 통해서 사용할 수 있습니다. Window 객체가 창을 의미한다면 Document 객체는 윈도우에 로드된 문서를 의미한다고 할 수 있습니다.

제어 대상을 찾기

브라우저가 만든 객체를 찾는 것

*document.getElementsByTagName : 태그의 이름이 li인 객체를 리턴합니다.

ul태그 내에 있는 li에 해당하는 객체를 찾으려면 즉 조회의 대상을 좁히려면

var ul = = document.getElementsByTagName('ul’)[0];

var lis = ul.getElementsByTagName('li');

    for(var i=0; i < lis.length; i++){

        lis[i].style.color='red';  

    }

*document.getElementsByClassName : className‘active’ 엘리먼트를 조회

var lis = document.getElementsByClassName('active');

    for(var i=0; i < lis.length; i++){

        lis[i].style.color='red';  

    }

*document.getElementById : 하나의 결과만을 조회, id‘active’ 엘리먼트를 조회

var li = document.getElementById('active');

li.style.color='red';

문서에서 id는 유일무이한 식별자 값이기 때문에 하나의 값이 됩니다.

*document.querySelector : 선택자를 인자로 받아 해당하는 엘리먼트를 리턴

var li = document.querySelector('li');

li.style.color='red';

var li = document.querySelector('.active');

li.style.color='blue';

jQuery(자바스크립트 라이브러리)

DOM을 내부에 감추고 보다 쉽게 웹 페이지를 조작할 수 있도록 돕는 도구

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <!--jquery사용법, http://와 같게 동작 -->

<script src=”../lib/jQuery/jquery-1.11.0.min.js”> <!--같은 방법-->

<script>

    jQuery( document ).ready(function( $ ) {

      $('body').prepend('<h1>Hello world</h1>'); // prepend() : 추가하는 메소드

    });

</script>


제어 대상을 찾기(jQuery)

jQuery의 기본 문법은 단순하고 강력합니다.

$() jquery function . 은 엘리먼트를 재어하는 다양한 메소드

Jquery 객체 : jquery function함수를 통해 리턴된 값

Jquery dom의 차이

코딩의 길이가 다름, 코드작성이 수월함, 빠르게 처리 가능

클래스명을 줄 때 .을 쓴다.

Id값은 #을 사용, 코드의 중복 사용을 없앨 수 있음(Chaining)

HTMLElement

 
  • HTML
  • CSS
  • JavaScript
 

document.getElementById : 리턴 데이터 타입은 HTMLLIELement, 1개만 리턴

document.getElementsByTagName : 리턴 데이터 타입은 HTMLCollection, 복수개를 리턴

 

링크는 href속성이 있어 href는 주소를 나타냄

Input의 경우 type, value의 속성이 있음

각각의 성격과 쓰임과 스펙에 따라 의미가 다름

 
opentutorials
  • HTML
  • CSS
  • JavaScript
 

 

모든 엘리먼트는 HTMLElement의 자식입니다. 따라서 HTMLElement의 프로퍼티를 똑같이 가지고 있습니다. 동시에 엘리먼트의 성격에 따라서 자신만의 프로퍼티를 가지고 있는데 이것은 엘리먼트의 성격에 따라서 달라집니다. HTMLElement Element의 자식이고 Element Node의 자식입니다. Node Object의 자식입니다. 이러한 관계를 DOM Tree라고 합니다.

HTMLCollection

리턴 결과가 복수인 경우에 사용하게 되는 객체

 

jQuery 객체

var li = $(‘li’); jquery function, li jquery object

li.css(‘text-decoration’, ‘underline’); //암시적 반복

 

jquery 객체 조회하기

 


 

Map()함수를 사용해 조회 결과 이용

 


 



출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

HTML CSS JavaScript(웹 페이지를 제어하는 역할)

HTML에서 JavaScript로드하기

Inline 방식은 태그에 직접 자바스크립트를 직접 기술하는 방식입니다.

장점은 연관된 스크립트가 분명하게 드러난다는 점입니다. 하지만 정보와 제어가 같이 있기 때문에 정보로서 가치가 떨어집니다.

<input type="button" onclick="alert('Hello world')" value="Hello world" />

<script>태그 이용

<input type="button" id="hw" value="Hello world" />

<script type="text/javascript">

    var hw = document.getElementById('hw');

    hw.addEventListener('click', function(){

        alert('Hello world');

    })

</script>

html코드 안에 자바스크립트가 존재하지 않습니다. 또한, 자바스크립트 유지보수하기에 바람직합니다.

외부 파일로 분리

정보와 제어의 결합도를 낯추며 유지보수의 편의성이 높아집니다.

<script src="./script2.js"></script>

script2.js  파일 내 코드

var hw = document.getElementById('hw');

hw.addEventListener('click', function(){

    alert('Hello world');

})

Script파일의 위치

  

head 태그에 위치시킬 수 있지만 이 경우는 오류가 발생할 수 있습니다.

Id hw의 존재를 해석하기 전의 상태에서 조회를 하고 있기 때문에 null의 상태가 됩니다. 존재하지 않는 객체를 호출한 상태이기 때문에 오류가 발생합니다.

window.onload = function(){

    var hw = document.getElementById('hw');

    hw.addEventListener('click', function(){

        alert('Hello world');

    })

} //윈도우 객체 onload를 호출하도록 약속, 태그가 화면이 등장한 이후 스크립트 //코드가 실행되기 때문에 오류를 없앨 수 있습니다.

script 파일은 head 태그 보다 페이지의 하단에 위치시키는 것이 더 좋은 방법입니다.


Object Model

객체화란 무엇인가?



테두리와 같은 역할을 합니다.

각각의 태그마다 객체를 만들어 준비를 해놓은 상태, 태그에 해당하는 객체를 찾아 메소드를 호출하거나 프로퍼티를 가져오는 것

객체화 = 객체 제어 방법

var imgs = document.getElementsByTagName(‘img’);

imgs[0].style.width=’300px’;

 

JavaScript Core, BOM DOM(윈도우 객체의 프로퍼티)

window : 전역객체

JavaScript Core : JavaScript 언어 자체에 정의되어 있는 객체들

BOM(Browser Object Model) : 웹페이지의 내용을 제외한 브라우저의 각종 요소들을 객체화시킨 것

DOM(Document Object Model) : 웹페이지의 내용을 제어


출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

+ Recent posts