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
반응형

+ Recent posts