I'm beginning to teach myself javascript. I thought I would try to make a script that embeds a youtube video when provided with a URL. Can anyone help me understand what I'm doing wrong when I create the iframe element, set the attributes, and append it as a child to the div? I'm using JSFiddle, and when I inspect the element no tag appears to have been added to the div. Thanks!
Edit: Here's my jsfiddle link: http://jsfiddle.net/86W8N/2/
<p>Click the button to call function</p> YoutubeURL: <input id="url" type="text"> <button onclick="myFunction()">Try it</button> <div id="video_div"> </div> <script> function myFunction() { var urlValue = document.getElementById("url").value; var videoID = urlValue.substring(urlValue.indexOf('=') + 1); var video = document.createElement("iframe"); video.setAttribute(title, "Test"); video.setAttribute(width, "440"); video.setAttribute(height, "390"); video.setAttribute(src, "http://www.youtube.com/embed/" + videoID); video.setAttribute(frameborder, "0"); var div_element = document.getElementById("video_div"); div_element.appendChild(video); } </script>
createElement() is used to dynamically create an HTML element node with the specified name via JavaScript. This method takes the name of the element as the parameter and creates that element node.
#1) createElement is more performant However, using the innerHTML causes the web browsers to reparse and recreate all DOM nodes inside the div element. Therefore, it is less efficient than creating a new element and appending to the div.
The document. createElement() accepts an HTML tag name and returns a new Node with the Element type.
append() allows you to also append string objects, whereas Node. appendChild() only accepts Node objects. Element. append() has no return value, whereas Node.
Your code will stop executing, throwing a title is not defined
exception at
video.setAttribute(title, "Test");
In setAttribute(title, ...)
you're using title
as though it was a variable named title, but that doesn't exist. You want instead to pass the string value "title"
:
video.setAttribute('title', 'Test');
... and the same for the other attributes...
A few more hints since you're using JSFiddle:
You need to wrap your attributes in quotes '
or double quotes "
:
video.setAttribute('title', "Test"); video.setAttribute('width', "440"); video.setAttribute('height', "390"); video.setAttribute('src', "http://www.youtube.com/embed/" + videoID); video.setAttribute('frameborder', "0");
Fiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With