[jQuery] 3. 문서 객체 조작

앙버터·2023년 12월 7일
0

Web Programming

목록 보기
6/7

3.1 문서 객체의 클래스 속성 추가 : addClass()

<script>
        $(document).ready(function () {
            $('h1').addClass('item');

            $('h1').addClass(function (index) {
                    return 'class' + index;
            });
    });
    </script>

3.2 문서 객체의 클래스 속성 제거 : removeClass()

$(document).ready(function () {
            $('h1').removeClass('select');
        });

3.3 문서 객체의 클래스 속성 검사 : attr()

  • 속성과 관련된 모든 기능을 처리
<script>
        $(document).ready(function () {
            // $('img') => 3개의 object
            // attr('src') => 3개의 image object중에서 첫번째 src값을 return
            var src = $('img').attr('src');

            alert(src);
</script>

3.4 문서 객체의 속성 추가 : attr()

$(selector).attr(name, value);
$(selector).attr(name, function(index, attr) {});
$(selector).attr(object);
			$('img').attr('width', 500);

            $('img').attr('width', function (index) {
                return (index + 1) * 100;
            });

            $('img').attr({
                width: function (index) {
                    return (index + 1) * 100;
                },
                height: 100
            });

3.5 문서 객체의 속성 제거 : removeAttr(name)

$(document).ready(function () {
            $('h1').removeAttr('data-index');
});

3.6 문서 객체의 스타일 검사 : css()

  • 스타일과 관련된 모든 기능을 수행
$(document).ready(function () {
            var color = ['red', 'yellow', 'purple'];

            // 문서 객체의 스타일을 변경합니다.
            $('h1').css('color', function (index) {
                return color[index];
            });
});

3.6 문서 객체의 스타일 추가 : css()

$(selector).css(name, value);
$(selector).css(name, function(index, style){});
$(selector).css(object);
$('h1').css({
	color: function (index) {
	return color[index];
	},
	backgroundColor: 'black'
});

3.7 문서 객체의 내부 검사 : html()

$(document).ready(function () {
            // 변수를 선언합니다.
            // $('h1') => 3개 h1 object 가져옴
            // html() => 3개 h1 object중에서 첫번째 객체의 text를 가져옴
            var html = $('h1').html();

            // 출력합니다.   
            alert(html);

            // html()메소드의 인자로 tag를 넣으면, tag가 적용됨
            $('div').html('<h1>$().html() Method</h1>');
  
            $('div').html(function (index) {
                return '<h1>Header-' + index + '</h1>';
            });
});

3.8 문서 객체의 내부 검사 : text()

$(document).ready(function () { 
            // 변수를 선언합니다.
            // $('h1').text() => h1 객체 3개의 모든 text를 가져옴
            var text = $('h1').text();
            // 출력합니다.
            alert(text);

            // text()메소드에 tag를 인자값으로 넣어도 tag로 인식을 안함.
            $('div').text('<h1>$().html() Method</h1>');
        });

3.9 문서 객체의 내부 추가

  • 문서 객체의 내부에 내용물을 추가하고 싶을 때
$(selector).html(value);
$(selector).text(value);
$(selector).html(function(index, html){});
$(selector).text(function(index, text){});

3.10 문서 객체 제거 : remove(), empty()

  • empty() : 문서 객체 내부 비움 (자식, 후손을 삭제/본인 삭제X)
  • remove() : 문서 객체 제거 (본인 포함 모두 삭제)

    empty() 는 본인 안의 내용을 비우고, remove() 는 전부 삭제한다고 이해

		$(document).ready(function () {
        	$('h1').first().remove();
        });

        $(document).ready(function () {
            // empty() => 자식, 후손 객체들을 삭제 (본인은 삭제가 안됨)
            // remove() => 본인을 포함하여, 자식, 후손객체 모두 삭제
            $('div').empty();
        });

3.11 문서 객체 생성(1) : $()

  • $() 메서드는 선택자로 문서 객체를 선택하는 기능 외에도 문서 객체를 생성하는 기능이 있음

3.12 문서 객체 생성(2)

  • 텍스트 노드를 갖지 않는 문서 객체 생성
<script>
        $(document).ready(function () {
        	// $('<h1></h1>') : html 태그를 넣어 문서 객체 생성
            // .html('Hello World .. !'): 텍스트 노드 추가
            // .appendTo('body'); : 문서 객체 연결
            $('<h1></h1>').html('Hello World .. !').appendTo('body');
            
			// 간단한 표현
            $('<h1>Hello World .. !</h1>').appendTo('body');

			// $('<img />') : 문서 객체 생성
            // attr('src', 'first.jpg') : 속성 추가
            // .appendTo('body') : 문서 객체 연결
            $('<img />').attr('src', 'first.jpg').appendTo('body');

            $('<img />', {
                src: 'first.jpg',
                width: 350,
                height: 250
            }).appendTo('body');

            
            // 변수를 선언합니다.
            var h1 = '<h1>Header1</h1>';
            var h2 = '<h2>Header2</h2>';

            // 문서 객체를 추가합니다.
            $('body').append(h1, h2, h1, h2);

        });
    </script>

3.13 문서 객체 삽입(1)

// $(document) => javascript object data type => {}
        $(document).ready(function () {
            // 변수를 선언합니다.
            var content = [
                { name: '윤인성', region: '서울특별시 강서구' },
                { name: '윤하린', region: '서울특별시 광진구' },
                { name: '윤인아', region: '미국 메사추세츠' }
            ];

            // 문서 객체를 추가합니다.
            // $('div') => document.getElementsByTagName
            // $('div') => div 객체 3개를 가져옴
            // $('div').append(function(){}) => 3개 div 객체에 대해서 function수행
            $('div').append(function (index) {
                // index가 0인 item = { name: '윤인성', region: '서울특별시 강서구' };
                var item = content[index];
                var output = '';
                output += '<h1>' + item.name + '</h1>';
                output += '<h2>' + item.region + '</h2>';
                // output = '<h1>' + item.name + '</h1><h2>' + item.region + '</h2>'
                return output;
            });
        });

3.14 문서 객체 삽입(2)

$(selector).append(content, content, ... , content)
$(selector).append(function (index) {});

3.15 문서 객체 이동

<script>
        $(document).ready(function () {
            // .image의 크기를 조정합니다.
            // $('img') => <img> 객체 3개를 return
            $('img').css('width', 250);

            // 함수를 2초마다 실행합니다.
            // 2000 => 2000 milisecond => 2초
            setInterval(function () {
                // 첫 번째 이미지를 마지막으로 보냅니다.
                // first() => <img>객체 3개중에 첫번째를 선택
                // append를 할 객체가 이미 html에 존재하면, jquery는 
                // 기존 위치에 있는객체는 삭제하고 새로 변경되는 위치에 추가(이동)
                $('img').first().appendTo('body');
            }, 2000);
        });
    </script>

3.16 문서 객체 복제 : clone()

profile
그래도 해야지 어떡해

0개의 댓글