Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill div with html using javascript/jquery

here is my problem:

I have a div:

<div id="legend"></div>

and I want to fill it, under certain conditions, with this other code:

<p>Showing results....
    Key:
    <img src="/....">&lt;=1
    &nbsp;<img src="/...">&lt;=2
    &nbsp;<img src="/...">&lt;=3
    &nbsp;<img src="/...">&lt;=4
    &nbsp;<img src="/...">&lt;=5

<p>

As you can see this is a legend and the main issue I think is that I have double quotes that cannot be easily included using for instance the solution here: Fill div with text

Thanks for your help!

like image 205
valenz Avatar asked Apr 15 '13 15:04

valenz


2 Answers

By my understanding, you are trying to do something like this:

$("#legend").text("Your HTML here");

To insert HTML, you should use .html(), HOWEVER it would be far more efficient to just use Vanilla JS like so:

document.getElementById('legend').innerHTML = "Your HTML here";

Now, you also mention having problems with double-quotes. Well, there are two possible solutions.

1: Use single-quotes around your string: '<img src="/..." />'
2: Escape the quotes: "<img src=\"/...\" />"

And one more thing: If those newlines are actually in your HTML to insert, you can't have a multi-line string in JavaScript. You have two options here too:

1: Escape the newline:

"<p>\
    Hello, world!\
</p>"

2: Concatenate:

"<p>\n"
    +"Hello, world!\n"
+"</p>"
like image 186
Niet the Dark Absol Avatar answered Oct 21 '22 10:10

Niet the Dark Absol


Assemble your html code in a variable according to your conditions (which we do not know), then use html() to set it to the element.

var yourHtml = "your html";
$("#legend").html("yourHtml");

As for dealing with the quotes, you can either use single quotes in variable, such as:

var yourHtml = '<img src="/yourimgr.png">';

or you can escape the double quotes:

var yourHtml = "<img src=\"/yourimgr.png\">";
like image 6
Adriano Carneiro Avatar answered Oct 21 '22 09:10

Adriano Carneiro