更改div的结构内容(没有JQuery)

时间:2014-07-01 14:36:52

标签: javascript

对不起,如果你发现这个问题愚蠢,但也许是因为是晚上,我找不到解决方案。

基本上,我用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();
    }
}

但是第二种情况不起作用,它什么都不做,而且div保持不变。 :X 如果我控制台.log容器和createDivStructure();我有好结果。

所以这是问题,有谁知道怎么做?如何用我创建的新div替换容器?

你是:D

1 个答案:

答案 0 :(得分: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);
    }
}