Grow your CSS skills. Land your dream job.

document.write to a specific id

  • # February 14, 2013 at 7:03 am

    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

    # February 14, 2013 at 7:24 am

    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.

    # February 14, 2013 at 7:27 am

    Can you not use ‘insertAfter’ instead of ‘append’?

    # February 14, 2013 at 7:42 am

    Paulie_D, Could you show me an example? :)

    # February 14, 2013 at 8:19 am

    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.

    # February 14, 2013 at 9:34 am

    Try this script instead:

    Check out [innerHTML](https://developer.mozilla.org/en/docs/DOM/element.innerHTML)

    The jQuery version would be:

    # February 14, 2013 at 4:27 pm

    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!

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".