2010-06-14 5 views
2

부모 요소 내부의 모든 요소를 ​​감지하고 자식 요소에 자식 요소가 있는지 확인하고 그 요소도 검색하고 싶습니다. 예를 들어상위 요소 내부의 요소를 감지하는 방법이 있습니까?

:

<div id="first"> 
    <div id='second1'></div> 
    <div id='second2'> 
      <div id='third1'></div> 
      <div id='third2'> 
       <div id='fourth1'></div> 
       <div id='fourth2'></div> 
      </div> 
      <div id='third3'></div> 
    </div> 
    <div id='second3'></div> 
    <div id='second4'></div> 
</div> 

나는 #first 내부의 모든 ID의 목록을 알고 그것의 아이가있는 경우 각각의 아이를 확인하고 나는 모든 요소의 전체 목록을 때까지가는이을 유지하려면 .

$("#first *") 

당신은 아이들

$("#first").children() 

추가를 얻기 위해 어린이 방법을 사용할 수 있습니다 :

나는

array (
"body"=> { 
      "first" => "second1", "second2" ............. 
     } 
); 
+0

배열 모양을하는 방법을 예를 제공? – jantimon

+0

이미 DOM이 있습니다. 너는 무엇을 성취하려고 하는가? – SilentGhost

+0

@silentghost가있다 내가 달성하기 위해 노력하고, getChild (ElementName에) 같은 함수를 만들고 내가 예를 – Starx

답변

2

이 시도 좀이 패턴의 배열이 목록을 원하는 약간의 재귀

function recursion (elem, arr) 
{ 
    var id = $(elem).attr('id'); 
    if (id) 
    { 
    var children = arr[ id ] = {}; 
    $(elem).children().each(function(){ recursion(this, children) }); 
    } 
} 

var elements = {}; 
recursion ($("#first"), elements); 
console.log (JSON.stringify(elements)); 

당신은

{"first":{"second1":{},"second2":{"third1":{},"third2":{"fourth1":{},"fourth2":{}},"third3":{}},"second3":{},"second4":{}}} 

http://jsbin.com/udaje4/edit

+0

아니, 아니에 보여처럼 배열 자식 ID를 검색하는 데, 그 때문에, 배열을 유지하려면 나는 그것들을 즉시 조작 할 수 없다. 어쨌든 고마워요 – Starx

+0

@Starx :이 방법이 효과가 있습니까? – jantimon

0

또 다른 방법이 될 것이다 얻을 것이다 : 당신이 수 plz 수

var childrens = {}; 
$('#first').children().each(function() { 
    id = $(this).attr('id'); 

    if($('#'+id).children().size() > 0) { 
     $('#'+id).children().each(function() { 
      childrens[id] = {} 
      childrens[id][$(this).attr('id')] = {}; 
     }); 
    } else childrens[$(this).attr('id')] = {}; 
}); 

alert(JSON.stringify(childrens)); 
+1

이것은 3 학년 어린이를 표시하지 않습니까? – jantimon

+0

아니, 그 또 다른 접근법, 실 거예요,하지만 결국에는 어느 쪽이든 재귀로 끝날 것입니다 :) 그게 당신이 내게 +1있어 – realshadow

관련 문제