next()/prev()

같은 형제 계열 중 에서 전/후 요소 선택하기

자바스크립트에서 

nextElementSibling와 previousElimentbling 를 사용하는 것과 같음

 

우선폼 먼저

 <fieldset>
    <legend>next() 및 prev()함수</legend>
    <button id="next">다음</button>
    <button id="prev">이전</button>
    <button id="continue" >계속</button>
    <ul>
     <li>JAVA</li>
     <li>JSP</li>
     <li id="third">FRAMEWORK</li>
     <li>JQUERY1</li>
     <li>JQUERY2</li>
     <li>JQUERY3</li>		
     <li>JQUERY4</li>
    </ul>			
 </fieldset>

id 속성이 있는 framework를 기준으로 속성을 줄거

next()

다음 버튼을 누르면 framework의 다음 글자에 css속성을 넣을 거임

$('#next').click(function(){
	 	제이쿼리 사용 시 한줄이면 끝
     $('#third').next().css({color:'red',fontSize:'1.8rem'});
        
        위 코드를 바닐라를 사용하면
        var third =document.querySelector('#third');
        var nextSibling = third.nextElementSibling;
        nextSibling.style.color='red';
        nextSibling.style.fontSize='1.8em';
            =>css속성 주는건 한줄로 줄이는게 가능
            nextSibling.style="color:red;font-size:1.8em";
             ==> setattribute 함수를 사용해도 가능
     		nextSibling.setAttribute('style','color:red;font-size:1.8em');
    });

 

prev()

이건 이전 형제들을 선택하는 함수

역시 기준은 framework로 잡고 구현

$('#prev').click(function(){
		제이쿼리사용
       $('#third').prev().css({color:'red',fontSize:'1.8rem'});
        
        바닐라 js로 변경시는 nextSibling을 previousElimentbling로 만 변경
       var third =document.querySelector('#third');
       var prebSibling = third.previousElimentbling;
       prebSibling .style.color='red';
       prebSibling .style.fontSize='1.8em';
 });

 

null혹은 undefined가 아닌 제이쿼리 객체를 무조건반환! 
 ******그래서 찾을 요소가 없는 것은 length로 판단한다!********

$('#continue').click(function(){
   console.log($('#third').prev().prev().html())   // JAVA가 잘 나옴
   console.log($('#third').prev().prev().prev().html())  // undefined가 나옴 이전이 없으니까

	console.log($('#third').prev().prev().prev())  //Object { length: 0, prevObject: {…} } 오잉?
 	console.log($('#third').prev().prev().prev().length == 0 )  //true 
});

 

//문제!

    //첫 번째 li 객체 저장
    var liObj = $('li:first');
    //마지막 객체여부 판단용 변수
    var index = 0;
    //li 객체의 전체수
    var length =$('li').length;

$('#continue').click(function(){   
    //index가 0일 때 즉 최초 버튼클릭 시
    if(index===0) $('li:last').css({color:'black',fontSize:'1em'});
   
   else{//이전 li객체를 원래대로
        liObj.prev().css({color:'black',fontSize:'1em'});
    }
    //해당 li객체를 css변경
    liObj.css({color:'red',fontSize:'1.8rem'});
    //인덱스 증가
    index++
    if(index != length)
   		liObj = liObj.next();
    else{
        //인텍스 다시 0
        index=0;
        //liObj에 처음 li객체를 저장
        liObj = $('li:first');
  }

});

 


[Siblings()]

siblings() : 모든 형제들 요소를 반환 한다.

폼 먼저

<fieldset>
    <legend>siblings([선택자])</legend>
    <div>
      <span>Hello</span>
    </div>
    <p class="selected">Hello Again</p>
    <p>And Again</p>
</fieldset>

 

 //요 둘의 차이는 자신을 포함 하느냐 안하느냐
 console.log($('p').siblings());  // 0: legend, 1: div, 2: p.selected, 3: p 요렇게 총 4개나옴
 console.log($('p.selected').siblings()); //Object { 0: legend, 1: div, 2: p} 요렇게 총 3개

 

$(p.selected)를 요렇게도 표현 가능하넴

$('div').siblings('.selected').css('background-color','yellow')

적용 잘 됨

each 함수적용도 가능함

each()함수 : 요소 하나하나에 함수를 적용시키겠다...

$('p').siblings().each(function(index,item){  
        ******item은 자바스크립트 객체이다!!!(제이쿼리객체가아님)
          //  console.log(item.innerHTML); 찍어보면 <span>Hello</span> 가 나옴
        if(item.nodeName ==='DIV')
            console.log(item.firstElementChild.innerHTML);  //콘솔창에 span태그 없애려고 나눔 !!
        else
            console.log(item.innerHTML);
     });

 


Parent

부모요소 얻기

 

<fieldset>
    <legend>parent([선택자])함수</legend>
    <button>부모얻기</button>

    <div class="div">
      <div>자식1</div>
      <div >자식2</div>
      <div class="third">자식3</div>
    </div>
    <ul>
     <li>JAVA</li>
     <li>JSP</li>
     <li class="third">FRAMEWORK</li>
     <li>JQUERY1</li>
     <li>JQUERY2</li>
     <li>JQUERY3</li>		
     <li>JQUERY4</li>
    </ul>	
 </fieldset>

 

부모찾기

 $('button').click(function(){
        console.log($('.third').parent())  // Object { 0: div.div, 1: ul, length: 2} 2개얌
        //모든 부모에 배경색 지정
        $('.third').parent().css('background-color','yellow');
        //부모중 div만 배경색 지정 () 안에만 지정해 주면 되넴?!!
        $('.third').parent('.div').css('background-color','yellow');

        //div는 배경색, 콘솔에는 버튼의 컨텐츠 출력! 한 번에 적용 됨! 오 짱신기
     console.log($('.third').parent('.div').css('background-color','yellow').prev().html())

    	 위를 바닐라로 
     console.log(document.querySelectorAll('.third')); // 타입확인 NodeList [ div.third, li.third ]
    document.querySelectorAll('.third').forEach(function(item){
        console.log(item.parentElement); div랑 ul 태그가 같이 나오넴
        console.log(item.parentElement.nodeName);   // 진짜 div랑 ul 글자만 나옴
        if(item.parentElement.nodeName== 'DIV'){
            item.parentElement.style.backgroundColor='yellow';
            console.log(item.parentElement.previousElementSibling.textContent);
        }          
    })
 });

 

 

이건 형제요소 찾기 연습인듯

<h2>형제요소찾기 연습</h2>
<input type="text" />	
<input type="button" value="등록" />	
<hr/>
<table cellspacing="1" bgcolor="gray" width="60%">
        <tr bgcolor="white">
            <th>번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>작성일</th>
    <th>삭제</th>
        </tr>
        <tr bgcolor="white" title="1">
            <td>1</td>
            <td>제목1</td>
            <td>작성자1</td>
            <td>2013-9-12</td>
    <td><input type="button" class="delete" value="삭제"/></td>
        </tr>
        <tr bgcolor="white" title="2">
            <td>2</td>
            <td>제목2</td>
            <td>작성자2</td>
            <td>2013-9-12</td>
    <td><input type="button" class="delete" value="삭제"/></td>
        </tr>
        <tr bgcolor="white" title="3">
            <td>3</td>
            <td>제목3</td>
            <td>작성자3</td>
            <td>2013-9-12</td>
    <td><input type="button" class="delete" value="삭제"/></td>
        </tr>
        <tr bgcolor="white" title="4">
            <td>4</td>
            <td>제목4</td>
            <td>작성자4</td>
            <td>2013-9-12</td>
            <td><input type="button" class="delete" value="삭제"/></td>
        </tr>
  </table>

 

 

***댓글 게시판 에서 댓글수정 시 사용했던 코드 여기있다 !!!!******

  	테이블에 마우스오버 기능
$('tr').slice(1).hover(function(){
    $(this).css({backgroundColor:'yellow',cursor:'pointer'});
},function(){
    $(this).css({backgroundColor:'white'});
})

테이블에 클릭 기능 이거!!!!! 게시판 만들 때 댓글 수정에 적용한 그거 !!!!****
$('tr').slice(1).click(function(){
    $('input[type=text]').val($(this).children(':eq(1)').html());
    $('input[type=button]').filter('[value=등록]').val('수정');   //필터 쓴 거 잘보고 
})

$('.delete').click(function(){
    console.log('삭제하려는 글 번호:',$(this).parent().prev().prev().prev().prev().html()); 이것은 노가다
    console.log('삭제하려는 글 번호:',$(this).parent().siblings(':eq(0)').html);  //형제들 중 첫 번째
    console.log('삭제하려는 글 번호:',$(this).parent().siblings(':first').html()); // 동일
})

 

+ Recent posts