treehouse : what would you like to learn today?
Web Design Web Development iOS Development

document.write to a specific id

  • I've been trying to make a function which makes a new div when clicked.

    I use this code:

    <script type="text/javascript"> function printYTVideo(fileUrl) { var ytDiv = document.getElementById('ytgoeshere'); ytDiv.appendChild(document.write('<div id="imjusttesting"><div id="youtube"><iframe width="640" height="360" src="' + fileUrl + '" frameborder="0" allowfullscreen></iframe></div></div>')); } </script>

    ...and this code for activating it:

    <li onclick="printYTVideo('http://www.youtube.com/embed/9cIjg2BibAM?feature=player_detailpage')">Trailer</li>

    But when I activate it, it doesn't add that div, but it deletes the entire page content and prints the div. Any ideas? Thank you all!

    // Simon


    EDIT: Sorry for messy code

  • I think that's how document.write works after the page has loaded, it rewrites the whole document. Can't find any references now though.

  • Can you not use 'insertAfter' instead of 'append'?

  • Paulie_D, Could you show me an example? :)

  • Here's one using jQuery in document.ready mode. http://codepen.io/anon/pen/vFcuh

    Two functions:

    One using 'insertAfter' targeting putting something after a specific ID and the second 'appendTo' putting it after the content of the 'article'.

    Please note that I am VERY new to JQ and I'm just getting into it.

    Certainly you could create a function and assign that function to a click event...but I'm still learning.

  • Try this script instead:

      <script type="text/javascript">
          function printYTVideo(fileUrl){
              var ytDiv = document.getElementById('ytgoeshere'); 
              ytDiv.innerHTML = '<div id="imjusttesting"><div id="youtube"><iframe width="640" height="360" src="' + fileUrl + '" frameborder="0" allowfullscreen></iframe></div></div>'; 
          }
      </script>
    

    Check out innerHTML

    The jQuery version would be:

      <script type="text/javascript">
          function printYTVideo(fileUrl){
              var $ytDiv = $('#ytgoeshere'),
                  content = '<div id="imjusttesting"><div id="youtube"><iframe width="640" height="360" src="' + fileUrl + '" frameborder="0" allowfullscreen></iframe></div></div>';
              $ytDiv.html(content); 
          }
      </script>
    
  • Here's a simple fiddle that I made for appending some text to a div with an id: http://jsfiddle.net/LJdWc/.

    Please let me know if you need anything further!