happy cat image

everdevel

coding

login
알림X
  • 현재 댓글에 대한 답변만 표시합니다.
  • 표시할 댓글 이력이 없거나 로그인해 주세요.
























everdevel이 만든 무료 클라우드 개발환경을 소개합니다.

방문해 주셔서 감사합니다.

태그 찾기

find는 어떤 특정 태그 안에 속한 태그를 선택하는 기능을 갖고 있습니다.

말로하면 어려우니 소스를 보면서 이해를 해봅시다.

HTML

<div class="hello">
	<p>php</p>
	<b>html5</b>
	<h4>css3</h4>
</div>

위의 소스를 보면 hello안에 php html5 css3가 각각 다른 태그로 감싸져있습니다.

그럼 find()를 이용해서 h4클래스를 선택해 보겠습니다.

그리고 나서 hello 안에 있는 h4클래스만 빨간색 외곽선 쳐보겠습니다.

jQuery

  var hello = $('.hello');
  var h4 = hello.find('h4');
  h4.css('border',1px solid red');

결과

php

html5

css3

위의 결과를 보면 h4태그인 css3에만 빨간색 외곽선이 처리된것을 볼 수 있습니다. 에버디벨의 css의 영향을 받아서 위치들이 이상한데요. 신경쓰지 말아주세요.

소스

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>EVERDEVEL :: 제이쿼리 강좌</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.0.min.js" ></script>
<script type="text/javascript">
$(function(){
    var hello = $('.hello');
    var h4 = hello.find('h4');
    h4.css('border','1px solid red');
});
</script>
</head>
<body>
<div class="hello">
<p>php</p>
<b>html5</b>
<h4>css3</h4>
</div>
</body>
</html>

결과는 바로 아래에서 확인하겠습니다.

그럼 h4태그를 선택자로 쓰거나 하면 될텐데 왜 이렇게 하나라고 생각하실수 있는데요..
실무를 하다보면 아하 이럴때 써야하구나 라는 순간이 옵니다...

그럼 어떤 상황에 쓰면 좋을까요?

만약 똑같은 클래스명으로 된 엘리먼트를 this연산자를 사용하여 하위 엘리먼트의 특정 태그를 선택할 때 find를 사용하면 편리합니다.

예를 들어 다음과 같이

<div class="hello">
<p>php</p>
<b>html5</b>
</div>

<div class="hello">
<p>php</p>
<b>html5</b>
<h4>css3</h4>
</div>

<div class="hello">
<p>php</p>
<b>html5</b>
<h4>css3</h4>
</div>

위의 소스에 클릭한 hello 클래스의 b태그의 색을 변경한다고 하면

다음과 같은 코드는 작동하지 않습니다.

$(this + ' b').css('color','skyblue');

이럴때 find를 사용해 b태그를 선택합니다.

$(this).find('b').css('color','skyblue');

그럼 해봅시다.

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>EVERDEVEL :: 제이쿼리 강좌</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.0.min.js" ></script>
<script type="text/javascript">
$(function(){
    $('.hello').click(function(){
        $(this).find('b').css('color','skyblue');
    });
});
</script>
<style>
    .hello{border:1px solid skyblue;margin-bottom:20px}
</style>
</head>
<body>
    <div class="hello">
        <p>php</p>
        <b>html5</b>
    </div>

    <div class="hello">
        <p>php</p>
        <b>html5</b>
        <h4>css3</h4>
    </div>

    <div class="hello">
        <p>php</p>
        <b>html5</b>
        <h4>css3</h4>
    </div>
</body>
</html>

결과는 바로 아래에서 확인하겠습니다.

위의 코드를 실행하여 박스를 클릭하면 해당 박스의 b태그만 색이 변경됩니다.


봐주셔서 감사합니다. 문의 또는 잘못된 설명은 아래의 댓글에 부탁드립니다.
당신의 작은 누름이 저에게는 큰 희망이 됩니다.

컨텐츠의 내용을 더 보려면 바로 아래에서 확인할 수 있습니다.


    
    

강좌로 돌아가기

댓글 0개

정렬기준