Question

Trying to write a Javascript code that replaces all YouTube object tags with iFrames. Instead, the function I've written will replace the first <object>, then stops and discards all content after the said <object>.

If I use a different element, such as a line break <br>, it will successfully replace all the <object> tags with <br> and no content is lost.

function editVideoObjects(htmlContent) {

        // Index all the objects and add ID tags
        var objectTags = htmlContent.querySelectorAll("object");
        var numberOfObjects = objectTags.length;

        for (var r = 0; r < numberOfObjects; r += 1) {
            objectTags[r].setAttribute("id", "video" + r)
        }

        for (var j = 0; j < numberOfObjects; j += 1) {
            var currentObject = htmlContent.getElementById("video" + j);

            var videoEmbed = currentObject.querySelector("embed");
            if (videoEmbed != null) {
                var videoSrc = videoEmbed.getAttribute("src");
                //Script specific for YouTube videos.
                if (videoSrc.split(".")[1] == "youtube") {
                    var newSrc = videoSrc.replace("/v/", "/embed/");
                    var iFrame = document.createElement("iframe");
                    iFrame.setAttribute("src", newSrc);
                    iFrame.setAttribute("height", currentObject.getAttribute("height"));
                    iFrame.setAttribute("width", currentObject.getAttribute("width"));
                    iFrame.setAttribute("frameborder", "0");
                    iFrame.setAttribute("allowfullscreen");
                    iFrame.setAttribute("id", "iFrameVideo" + j);
                    $(currentObject, htmlContent).replaceWith(iFrame);
                    }
            }
        }
    }
Was it helpful?

Solution

Found a solution! I saved the function as an external file to be appended to the <head> in the main DOM whenever the corresponding article is called, instead of being nested in the primary Javascript file.

function itemInvoked(e) {
        var currentArticle = articlesList.getAt(e.detail.itemIndex);
        WinJS.Utilities.setInnerHTMLUnsafe(articlecontent, currentArticle.content);
        var videoScript = document.createElement("script");
        videoScript.type = "text/javascript";
        videoScript.src = "/js/videoEditScript.js"
        document.getElementsByTagName("head")[0].appendChild(videoScript);
        articlelist.style.display = "none";
        articlecontent.style.display = "";
        mainTitle.innerHTML = currentArticle.title; 
        WinJS.UI.Animation.enterPage(articlecontent);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top