본문 바로가기
jQuery/jQuery HTML

jQuery HTML Get Content and Attributes text(), html(), val(), attr()

by 진격의 파파 2013. 5. 17.
반응형

이번 장에서는 jQuery HTML을 어떻게 컨트롤 할 수 있는지에 대해서 알아보겠습니다.

jQuery 는 DOM을 조작할 수 있습니다. 

DOM 은 Document Object Model의 줄임말입니다.

 

Get Content text(), html(), val(), attr()

 

text() - 텍스트의 내용을 설정하거나 반환할 수 있습니다.

html() - 선택한 요소의 내용을 설정하거나 반환할 수 있습니다.

val() - 폼 필드의 값을 설정하거나 반환할 수 있습니다.

attr() - 속성값을 설정하거나 반환할 수 있습니다.

 

text(), html() 사용방법

 

간단한 예제

$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});

// text()는 text 내용만을 보여주며 html()은 html 요소까지 모두 나타냅니다.

 

관련예제

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    alert("Text: " + $("#test").text());
  });
  $("#btn2").click(function(){
    alert("HTML: " + $("#test").html());
  });
});

</script>
</head>

<body>
<p id="test">This is some <b>bold</b> text in a paragraph.</p>
<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>
</body>
</html>

 

 

// "show html" 버튼을 클릭하면 html 구문 전체를 메시지 창에 띄웁니다.

// "show text" 버튼을 클릭하면 text 내용만 메시지 창에 띄웁니다.

 

val() 사용방법

간단예제

$("#btn1").click(function(){
  alert("Value: " + $("#test").val());
});
// id text의 value값을 메시지 창에 띄우라는 내용입니다.
 
관련예제
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    alert("Value: " + $("#test").val());
  });
});

</script>
</head>
<body>
<p>Name: <input type="text" id="test" value="Park's의 블로그"></p>
<button>Show Value</button>
</body>
</html>

 

 
attr() 사용방법
간단예제
$("button").click(function(){
  alert($("#w3s").attr("href"));
});
// id w3s의 href값을 메시지 창에 띄우라는 내용입니다.

 

관련예제

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    alert($("#w3s").attr("href"));
  });
});
</script>
</head>

<body>
<p><a href="http://blog.naver.com/makand123" id="w3s">Park's의 블로그</a></p>
<button>Show href Value</button>
</body>
</html>

 

 

 

// 버튼을 클릭하면 href의 내용을 볼 수 있습니다.


다음 장에서는 jQuery 를 이용하여 text(), html(), val(), attr() 의 구문을 어떻게 변경할 수 있는지에 대해서 알아보겠습니다. 

반응형

'jQuery > jQuery HTML ' 카테고리의 다른 글

jQuery classes css()  (0) 2013.05.23
jQuery CSS Classes  (0) 2013.05.23
jQuery - Remove Elements  (0) 2013.05.22
jQuery Add Elements  (0) 2013.05.21
jQuery html Set text(), html(), val(), attr()  (0) 2013.05.20