not set

jQuery html(), text() 본문

javascript/jQuery

jQuery html(), text()

다크곰 2012. 2. 3. 15:45

<!doctype html>

<html>

<head>

    <title>jquery test</title>

    <script src="http://code.jquery.com/jquery-1.7.js"></script>

</head>

<body>

<script>

    $(document).ready(function () {

        // 변수 선언

var html = $('h1').html();


// 출력

alert(html);

    });

</script>

    <h1>Header-0</h1>

    <h1>Header-1</h1>

    <h1>Header-2</h1>

</body>

</html>


<!doctype html>

<html>

<head>

    <title>jquery test</title>

    <script src="http://code.jquery.com/jquery-1.7.js"></script>

</head>

<body>

<script>

    $(document).ready(function () {

        // 변수 선언

var text = $('h1').text();


// 출력

alert(text);

    });

</script>

    <h1>Header-0</h1>

    <h1>Header-1</h1>

    <h1>Header-2</h1>

</body>

</html>



위의 2가지 예제의 차이점을 무엇일까.

1번 html() 을 썼을땐

"Header-0" 이라는 alert 창이 나오는 반면에

2번 text() 를 썼을때는

"Header-0Header-1Header-2"  이렇게 문서 객체의 글자가 이어서 출력된다.

attr(), css(), html() 은 모두 하나만 출력되지만 text() 는 이어서 출력되는걸 명심!! 


■ 문서객체의 내부 추가

1. $(selector).html(value);
   $(selector).text(value);
2. $(selector).html(function(index, html) {});
   $(selector).text(function(index, html) {});



<!doctype html>

<html>

<head>

    <title>jquery test</title>

    <script src="http://code.jquery.com/jquery-1.7.js"></script>

</head>

<body>

<script>

    $(document).ready(function () {

$('div').html('<h1>$().html() Method</h1>');

    });

</script>

<div></div>

<div></div>

<div></div>

</body>

</html>


결과


본문 출처 : 모던 웹을 위한 Javascript 입문 및 jQuery입문