2013-11-27 4 views
1

나는 약간 혼란 스럽다. 나는 기본적인 DOM 조작을 시도했다. 즉, <head> 태그에 제목을 추가하여 테스트했다. 이것은 내가 쓴 것입니다 :JS : 머리에 요소를 추가하는 방법 - 방법을 연결하는 방법?

document.head.appendChild(document.createElement("title").appendChild(document.createTextNode("Test Title"))); 

그러나, 위의 작동하지 않습니다. 분할하면 작동 :

var node = document.createElement("title"); 
var text = document.createTextNode("Test title"); 
node.appendChild(text); 
document.head.appendChild(node); 

왜 내가 무엇을 놓치고 있습니까?

답변

8

메서드 체이닝은 이전 메서드의 반환 값에서 작동합니다.

var chain = { 
    example: function (val) { 
     alert(val); 
     return this; 
    } 
}; 
chain.example('this').example('works'); 

exampleexamplereturn this 때문에 다시 표시 example 방법을 가진 개체의 떨어져 체인 될 수있다.

parent.appendChild(child)의 경우 반환 값은 child입니다. 즉, 체인을 추가하면 parent에 요소가 추가되지 않고 이후 요소가 중첩됩니다.

+0

오 감사합니다, 나는 그것을 놓친 믿을 수 없다! – Fygo

1

제목 요소를 추가 한 다음 에 텍스트를 추가합니다 ( 개체 추가). 제목 요소는 특수한 경우입니다 경고 -

을 parentheses- 주, 단 하나의 제목 요소는 문서의 유효

document.head.appendChild(document.createElement("title")).appendChild(document.createTextNode("Test Title")); 
+0

그래, 이건 내가 성취하려고했던 것이지만, 나는 괄호를 엉망으로 만든다. 고마워! +1 – Fygo