using javascript to output html

I have a javascript link that references another .js file. I've been trying to output an image (for testing purposes), but I'm not sure what is the correct way to go about this.

    //var link = $("<a href=''>Hello, <b>World</b>!</a>");
    //document.write("<div><img src='' /></div>");
    alert("before function");

    var links = $("<a href=''>Hello, <b>World</b>!</a>");
    alert("after middle");
    document.write("<div><img src='' /></div>");


I was able to alert beginning, all the way to middle. It seems like var links doesn't work. I'm trying to use HTML inside this .js file. Essentially, I want to be able to do some modal window, but I'm trying to output images for testing purposes right now.

Also, is this the correct way for jquery?

Thanks in advance!


Your code is a strange mix. Jquery code almost always needs to run after the page has loaded whereas document.write can never be used after the page has loaded.

You are incorrectly wrapping your jQuery in an immediate executing function. The proper wrap for jQuery is within :

  /* html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have

or the shorthand version that does same thing:

  /*html of page exists now, run jQuery here */
});// notice no extra "()" after close brace  as you have

If you change all of your document.write to $('body').append(/* your content*/) and place all your code inside the above wrappers you will have much better success.

There is a wealth of information within the jQuery documentation and API. A good start point with more detail about the wrapping I've shown can be found here:

Your biggest problem is addressed in the other answer. You are improperly wrapping JQUery so essentially JQuery is not ready to be executed when it reaches your append statement.

It is unnecessary to wrap your html in a JQuery object (in this case):

var links = "<a href=''>Hello, <b>World</b>!</a>";

or simply:

$('body').append("<a href=''>Hello, <b>World</b>!</a>");

In terms of best practice, using append, appendTo or prepend are good options depending on the context. You could also use:

$("body").html("/*Your HTML here*/")

At the end of the day you have many options but avoid document.write at all cost. The non-JQuery approach would be to use .innerHTML with a DOM element. This is also a good approach in the absence of JQuery.

Need Your Help

Call Variable from reactive data() in R Shiny App

r shiny

I would like to call a certain variable within a reactive expression. Something like this:

Understanding arrayWithCapacity: method on NSMutableArray

objective-c nsmutablearray nsrangeexception

I'm having a hard time trying to understand a method in the Objective-C's NSMutableArray class. I created an array using the arrayWithCapacity: static method of this class, just like this: