2014-07-01 115 views
-1

对不起,如果你发现这个问题愚蠢,但也许是因为是晚上,我找不到解决方案。更改div的结构内容(无JQuery)

基本上,我在js中创建了一些div。例如

function a(){ 
    var div = createElement('div'); 
    var div2 = createElement('div'); 
    // I add stuff to div 2 
    var div3 = createElement('div'); 
    // I add stuff to div 3 

    div.appendChild(div2); 
    div.appendChild(div3); 

    return div; 
} 

然后我不得不说。在第一种情况下,我想将这个div添加到现有的div,并在第二我想修改这个现有的div。

我做类似的东西

function addOrModify(value,container){ 
    // if value = true i add this div to the container 
    if(value){ 
     container.appendChild(createDivStructure()); 
    } 
    //else i want my container to be like the div i created 
    else{ 
     container = createDivStructure(); 
    } 
} 

但第二种情况下不工作,它什么也不做,股利保持不变。 :x 如果我console.log容器和createDivStructure();我有很好的结果。

所以这里的问题,任何人都知道如何做到这一点?我如何可以用我创建的新div替换容器?

THX您:d

+0

请展开 “不起作用” – Smeegs

+0

我假设'container.appendChild(createDivStructure());'工作正常,你需要另一个人的帮助? – Cerbrus

+0

它什么都不做,div保持不变。我尝试删除第一个,并添加第二个,但她被添加到容器的末尾:/ @Cerberus是的抱歉我编辑 – Crocsx

回答

1

这应该做的伎俩:

function addOrModify(value,container){ 
    if(value){ 
     container.appendChild(createDivStructure()); // This seems just fine. 
    } else{ 
     // Insert the new element before the "Target": 
     container.parentElement.insertBefore(createDivStructure(), container); 
     // Remove the "Target": 
     container.parentElement.removeChild(container); 
    } 
} 
+0

天哪,太容易了......我一定很累。 Thx你这么多人:) '接受'在6分钟回答 – Crocsx

+0

人们经常忘记'insertBefore' ;-) – Cerbrus