2014-10-24 3 views
5

함수 .text()를 사용하여 요소 스팬에 텍스트를 쓰려고하는데이 오류가 발생했습니다. UncaughtTypeError : undefined가 함수이 아니며 append(), innerHtml(), createTextNode() 성공하지 못했습니다.document.createElement ("span"); 후 스팬에 텍스트를 추가하는 방법

내가 뭘 잘못하고 있니?

var span = $("span"); // create element span 
$(span).html("your text"); // add text 
$("#myDiv").append($(span)); // append it to the div element 
+1

'.text()'는 jQuery의 기능입니다. 'closeSpan.textContent = "Close"; 사용 jQuery의'.append()'DOM 버전이 무엇인지 모른다. – Regent

+1

'innerHTML' /'innerText' /'textContent'는 속성이 아니라 속성 ('span. innerHTML = '닫기'). 'createTextNode'는 텍스트 노드 만 만들고, 여전히 요소에 추가해야합니다 ('span.appendChild (document.createTextNode ('Close'))'). – hsan

+0

* "내가 뭘 잘못하고 있니?"* - jQuery와 DOM 메서드가 섞여있다. 왜 document.createElement()를 호출하는지 설명 할 수 있습니까? (또한 DOM 노드 객체에 대한 문서 (https://developer.mozilla.org/en-US/docs/Web/API/Node),'.text()'도 아니고'.append ()'존재합니다. – Tomalak

답변

14

당신이 순수 DOM 코드로 시작되기 때문에, 나는 순수 DOM 코드를 계속 좋을 것 :

var closeSpan = document.createElement("span"); 
closeSpan.setAttribute("class","sr-only"); 
closeSpan.textContent = "Close"; 

즉, textContent을 원하는 값으로 설정하면됩니다.

IE 8 또는 이전 버전과의 호환성 문제가있는 경우 구형 브라우저의 경우 textContent이 존재하지 않습니다. 그 오래된 것들은 innerText (IE 8에서는 작동하지만 표준의 일부는 아님)이나 innerHTML을 사용해야합니다. 이 필드들의 차이점에 대한 설명은 textContent의 MDN 페이지 (위의 링크 참조)를 참조하십시오.

0

+0

코드 편집 ... – anni

+0

완료되었습니다. 그 – Joe

+0

참고로 .append ($ (span)) 할 필요가 없습니다. 당신의 코드에서'span' *은 이미 jQuery 객체이고, .append (span)는 정상적으로 처리 할 것입니다. 또는'span.appendTo ("# myDiv")'. 그 변수에 대한 올바른 명명 규칙이'$ span'이었던 이유이기도합니다. – Tomalak

1

당신이 또한

var closeSpan = document.createElement("span"); 
closeSpan.setAttribute("class","sr-only"); 
closeSpan.html("Close"); 
을 시도 할 수 있습니다 : 당신이 ID가 "myDiv"로 사업부에 "범위"태그를 추가 할 가정

var closeSpan = document.createElement("span"); 
closeSpan.setAttribute("class","sr-only"); 
closeSpan.text("Close"); //UncaughtTypeError: undefined is not a function 

또는

var closeSpan = document.createElement("span"); 
closeSpan.setAttribute("class","sr-only"); 
closeSpan.append("Close"); //UncaughtTypeError: undefined is not a function 
0

이 아닌 경우 당신과 같이 closeSpan.appendChilddocument.createTextNode을 사용, jQuery를 사용하려면 :

var closeSpan = document.createElement("span"); 
closeSpan.setAttribute("class","sr-only"); 
closeSpan.appendChild(document.createTextNode("Close")); 

이 방법은 크로스 브라우저 호환성을 극대화합니다. 이전 버전의 IE를 포함하여 모든 브라우저에서 작동합니다.

당신이이 jQuery를 사용 하시겠습니까 경우에, 당신은 한 줄에이 작업을 수행 할 수 있습니다 :

var closeSpan = $("<span></span>").addClass("sr-only").text("Close")[0]; 
관련 문제