2012-01-05 1 views
1

자동 생성 된 텍스트 노드에 CSS 스타일을 추가하는 데 문제가 있습니다. textnode에는 부모 노드가 없다는 것을 알고 있습니다. 그래서 저는 CSS 스타일을 추가 할 수 없습니다.동적으로 텍스트 노드에 CSS 스타일 추가

기본적으로 사용자가해야 할 일은 사용자가 페이지에서 "+"버튼을 클릭하면 페이지에 새 텍스트 노드가 추가됩니다. 사용자가 한 번 더 클릭하면 다른 새로운 텍스트 노드가 계속 추가됩니다. 그러나 textnode를 만든 후에 CSS 스타일을 추가하고 싶습니다.

function addRowToTable() { 

//find the last row in the table and add the new textnode when user clicks on the button 
var tbl = document.getElementById('audioTable2'); 
var lastRow = tbl.rows.length; 
var iteration = lastRow; 
var row = tbl.insertRow(lastRow); 

//after find the last row in the table, and it will add the new cell with the new textnode 
    var cellLeft = row.insertCell(0); 
    var el_span = document.createElement('span'); 
    var el_spanClass = el_span.setAttribute('class', 'test'); 
    var textNode = document.createTextNode(iteration); 
    cellLeft.appendChild(textNode); 
} 

//this is the css style I would like to apply into the new gerenated textnode 
function appendStyle(styles){ 
    var css = document.createElement('style'); 
css.type='text/css'; 

if (css.styleSheet) css.styleSheet.cssText = styles; 
else css.appendChild(document.createTextNode(styles)); 
document.getElementsByTagName("head")[0].appendChild(css); 
} 

사람이 나를 도울 수 : 여기

내 코드? 고마워. "나는 textnode를 생성 한 자동으로 CSS 스타일을 추가하는 데 문제가있어" 을하지만 코드는 당신이 당신이 모든에 대해 headstyle 요소를 추가하려고하는 것을 보여줍니다 제공 :

+0

가능한 복제 -> http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript – ManseUK

답변

3

당신 말 새 텍스트 노드. 당신이 원하는 것은 1) 스타일 시트에 이미 정의 된 스타일을 텍스트 노드에 적용하거나 2) 직접 텍스트 노드 인라인 스타일을 지정하는 것입니다.

1) span를 통해 textnode에 CSS 스타일 시트에 스타일을 적용 :

//after find the last row in the table, and it will add the new cell with the new textnode 
    var cellLeft = row.insertCell(0); 
    var el_span = document.createElement('span'); 
    var el_spanClass = el_span.setAttribute('class', 'test'); 
    var textNode = document.createTextNode(iteration); 
    cellLeft.appendChild(el_span); 
    el_span.appendChild(textNode); 
} 

이 당신이하지 않는 (셀에 span을두고 따라서, 당신의 코드 중 하나를해야한다고 생각 당신의 코드에서 do) testclass을주는 범위와 함께 textnode를 감쌀 것입니다.

2)이 span를 통해 textnode에 직접 (인라인) 스타일을 적용 :

//after find the last row in the table, and it will add the new cell with the new textnode 
    var cellLeft = row.insertCell(0); 
    var el_span = document.createElement('span'); 
    el_span.setAttribute('style', 'color: red'); /*just an example, your styles set here*/ 
    var textNode = document.createTextNode(iteration); 
    cellLeft.appendChild(el_span); 
    el_span.appendChild(textNode); 
} 

을 각각의 경우에, 당신의 appendStyle 기능은 삭제 될 수 있습니다.

+0

모두 효과가 있습니다. 고마워. 두 방법 모두 유효합니다. –