2014-03-26 2 views
0

이 appendChild() method.but의 예제에서 작업하고 있습니다. 차이점은 여기에 있습니다. div에 동적으로 텍스트를 추가하려고합니다. 괜찮습니다. 그러나 어려운 부분은 텍스트입니다. 나는 color.How에 빨간색으로 추가 할 싶습니다. 은 내가동적으로 추가 된 텍스트에 색상을 추가하십시오.

text.setAttributes('color',"red"); 

을 시도하지만이 아니야! 전혀 그렇지 않았다,이 작업을 도와주세요 ?? 수행 할 수있는 방법, 감사 !!!! 즉 당신의 DIV에 모든 것이 있다면

전체 코드가 ............

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript"> 
function create_text(){ 
    var mydiv = document.getElementById("mydiv"); 
    var text = document.createTextNode(" New text to add."); 

    mydiv.appendChild(text); 
} 
</script> 
</head> 
<body> 
<button onclick="create_text();">Create Text Node</button> 
<div id="mydiv">Welcome, here is some text.</div> 
</body> 
</html> 
+0

, 당신은 요소에 속성으로 스타일을 설정하지 : 다음도 가능하다. 그들은 요소의'style' 객체로 가야합니다. –

답변

3

그러나, 텍스트 노드가 적용된 CSS 속성을 가질 수 없습니다. 따라서 다른 컨테이너 요소가 필요합니다.

원하는 컨테이너 요소를 선택할 수 있습니다. div, span 등. 텍스트 노드를 포함 할 수 있어야합니다. 그런 다음 요소를 사용하면 styles 속성에 액세스하고 다양한 스타일을 설정할 수 있습니다 (귀하의 경우에는 color 속성).

→ jsFiddle

function create_text(){ 
    var mydiv = document.getElementById("mydiv"); 

    var container = document.createElement("span"); 
    var text = document.createTextNode(" New text to add."); 

    container.appendChild(text); 
    container.style.color = "red"; 

    mydiv.appendChild(container); 
} 

또한 참고 :

  • 색상 지정 및 appendChild가 임의의 호출의 순서. 당신은 노드를 텍스트로 직접 스타일을 적용 할 수 없습니다

    function create_text(){ 
        var mydiv = document.getElementById("mydiv"); 
    
        var container = document.createElement("span"); 
        var text = document.createTextNode(" New text to add."); 
    
        container.appendChild(text); 
        mydiv.appendChild(container); 
    
        container.style.color = "red"; 
    } 
    
+0

감사합니다. !!! :) –

0

아래 주어, 당신이 시도 할 수

document.getElementById("mydiv").style.color="#ff0000"; 
0
mydiv.style.color = 'red'; 

또는 CSS로만 작성

#mydiv { color: red; } 

div 안에 다른 요소가있는 경우 빨간색이되고 싶지 않다면, 추가하기 전에 범위 나 div 또는 다른 요소에 새 텍스트를 래핑해야합니다.

jQuery로이 슈퍼 쉬운 것입니다 : 당신은 일반적으로 CSS 속성을 사용하는 것

$('#mydiv').append('<span style="color:red">this is new text</span>'); 
관련 문제