컨텐츠 가져 오기-text (), html (), val (), attr()

국물빌런·2020년 2월 24일
0

text()메소드는 해당 선택자가 가리키는 text를 가져온다.
html()메소드는 해당 선택자가 가리키는 태그까지 모두 가져온다

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.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>

text호출시 : Text: This is some bold text in a paragraph.
html호출시 : HTML: This is some bold text in a paragraph.

val()메소드 : 선택자가 가르키는 객체의 value값을 가져온다.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.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="Mickey Mouse"></p>

<button>Show Value</button>

</body>
</html>

결과는 Value: Mickey Mouse
물론 텍스트박스의 내용이 바뀌면 바뀐 내용을 가져옴
주로 input태그와 같이 쓰임

attr()메소드는 선택된 객체의 attribute값을 가져온다.

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

<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>

<button>Show href Value</button>

</body>
</html>

결과는 https://www.w3schools.com

출처 : w3 school

profile
국물을 달라

0개의 댓글