Why node.replaceChild does not work?

1

Good, I have a carousel of bootstrap in which, when I do click in the images that are replaced by a video server.

This is the code of one of the items:

<div class="item active" id="unboxing" onclick="PonerVideo(this)">
    <img src="img/unboxing.png">
</div>

And when I do click I call this function:

function PonerVideo(ele){
    var titulo = ele.id;
    var old = ele.firstChild;
    var node = document.createElement("div");
    var src = document.createElement("iframe");
    node.setAttribute("class", "embed-responsive embed-responsive-16by9");
    src.setAttribute("class","embed-responsive-item");
    src.setAttribute("src","img/"+titulo+".mp4" );
    src.setAttribute("onclick", "Pausa(this)");
    node.appendChild(src);
    ele.replaceChild(node,old);
}

The video works well, but what it does is move the photo below the video, instead of replacing it.

I tried to do remove child as well, but that left the photo in its place with the video below.

I put a iframe because otherwise the video does not fit inside the carousel item and it is not seen. The videos are from the server where the web is hosted, they are not from YouTube or anything like that.

I must be escaping something but I do not know what.

    
asked by Victor Galvez Lopez 23.01.2018 в 10:21
source

1 answer

3

The problem is that ele.firstChild returns the NodeText containing the text ( spaces ) from onclick="PonerVideo(this)"> to <img .

Solution 1:

You could use ele.firstElementChild , instead of using ele.firstChild :

  

The read-only property ParentNode.firstElementChild returns the first child of the object of type Element , or null if there are no child elements.

Example:

function PonerVideo(ele){
    var titulo = ele.id;
    var old = ele.firstElementChild;
    var node = document.createElement("div");
    var src = document.createElement("iframe");
    node.setAttribute("class", "embed-responsive embed-responsive-16by9");
    src.setAttribute("class","embed-responsive-item");
    src.setAttribute("src","img/"+titulo+".mp4" );
    src.setAttribute("onclick", "Pausa(this)");
    node.appendChild(src);
    ele.replaceChild(node,old);
}
<div class="item active" id="unboxing" onclick="PonerVideo(this)">
    <img src="img/unboxing.png">
</div>

Solution 2:

Modify the markup and delete the spaces.

<div class="item active" id="unboxing" onclick="PonerVideo(this)"><img src="img/unboxing.png"></div>
    
answered by 23.01.2018 / 11:14
source