2011-12-22 3 views
5

나는 litle 문제가 있으며 어떻게 수정해야할지 모르겠다.jQuery 업데이트 html 요소 텍스트가 HTML 자식 요소에 영향을주지 않고

이 나는 ​​HTML 계층 여기에 하나

<ul id="mylist"> 
    <li id="el_01"> 
     <div class="title"> 
      Title Goes Here 
      <span class="openClose"></span> 
     </div> 
    </li> 
</ul> 

내가 뭘 좋아하는 것은 "제목이 여기에 간다"수정처럼해야합니다.

$('#el_01 title').text('New Title Goes Here'); 

하지만 그 또한 제거 :

내가 시도를 경우에만 업데이트하는 방법 스팬 요소에 영향을 미치지 않고 "제목은 여기에 간다"

<span class="openClose"></span> 

있습니까?

답변

8

DOM 요소에 액세스하고 firstChild을 가져 와서 텍스트 노드를 직접 편집 할 수 있습니다. 여러 .title 요소가있는 경우

$('#el_01 .title')[0].firstChild.data = 'New Title Goes Here'; 

, 당신은 그것은 .each() 루프에서 할 수 있습니다.

$('#el_01 .title').each(function(i,el) { 
    el.firstChild.data = 'New Title Goes Here'; 
}); 
+1

매우 좋습니다! 감사 ! 몇 분 후에 대답으로 확인하겠습니다. –

2

두 가지 가능한 솔루션 :

다음 중 하나를 랩 자체의 범위에있는 텍스트 :

<div class="title"> 
    <span class="text">Title Goes Here</span> 
    <span class="openClose"></span> 
</div> 

... 그리고 그 업데이트 :

$('#el_01 .text').text('New Title Goes Here'); 

또는 : 사본 보관 O f openClose 스팬을 입력하고 텍스트를 업데이트 한 후 다시 삽입하십시오.

var openClose = $('#el_01 .title .openClose'); 
$('#el_01 .title').text('New Title Goes Here').append(openClose); 
관련 문제