본문

160124P(일)

웹브라우저 자바스크립트


조회 API

document.getElementsBy*

문서 전체의 엘리먼트를 조사


getElementById

해당 엘리먼트의 하위 엘리먼트를 대상으로 조회를 수행


<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>

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

    console.group('document');

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

        console.log(list[i].textContent);

    }

    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);

    }

    console.groupEnd();

</script>


속성 API

속성

태그명만으로는 부족한 부가적인 정보를 표현


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

<script>

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

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>


속성과 프로퍼티의 차이점

모든 엘리먼트 속성은 JavaScript의 속성과 프로퍼티로 제어가 가능하다.


<p id="target">

    Hello world

</p>

<script>

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


    // attribute 방식

    target.setAttribute('class', 'important');


    // property 방식

    target.className = 'important';

</script>


property방식이 통상적으로 더 빠르다.

하지만 HTML속성과 js의 속성이 다른이름을 갖는 경우가 많기 때문에 사용할 때 주의해야 할 점이 많다.


classclassName
readonlyreadOnly
rowspanrowSpan
colspancolSpan
usemapuserMap
frameborderframeBorder
forhtmlFor
maxlengthmaxLength


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

<script>

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

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


// property로 read

// http://localhost/webjs/Element/attribute_api/demo1.html 

console.log('target.href', target.href);


// attribute로 read

// ./demo1.html 

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

</script>


jQuery 속성 제어
setAttribute, getAttribute는 attr로 대응
removeAttribute는 remvoeAttr로 대응

<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도 속성과 프로퍼티를 구분

<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>



jQuery를 사용해서 property를 사용하면 내부적으로 이름을 보정해주기 때문에 이름이 달라서 생기는 어려움을 극복 가능하다.

<div id="t1">opentutorials</div>
<div id="t2">opentutorials</div>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$('#t1').prop('className', 'important');
$('#t2').prop('class', 'current');
</script>


jQuery 조회 범위 제한


selector context

조회할 때 조회 범위 제한


<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>

// 1번째 방법

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


// 2번째 방법

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

</script>


.find()

find를 사용해서 객체내의 특정 엘리먼트를 조회하는 것이 가능하다.


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

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

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



'낡은 서랍장 > JavaScript' 카테고리의 다른 글

160115P(금)  (0) 2016.01.15
160114P(목)  (0) 2016.01.14
160113P(수)  (0) 2016.01.13
160106P(수)  (0) 2016.01.06
160104P(월)  (0) 2016.01.05

공유

댓글