How can I insert HTML code inside javascript variable?

So, I am extracting information from the Google calendar, and I need to separate the variables that I get in order to display them in different divs. So what I need to do is something like this

var divMonth = '<div id ="rawr">'; var divMonthClose = '</div>'; dateString = divMonth + monthName + divMonthClose + ' | ' + parseInt(dateMonth, 10); 

However, what do you think the displayed result ...

 "<div id ="rawr">December</div> | 8" 

It does not actually interpret html and does not make a div layer. So my question is: how can I insert html code into a variable so that it really works like html? Is there a function that I'm missing or is this possible?

Thanks in advance for any help or ideas you may have!

+6
source share
5 answers

You have a post marked as jquery, so you can do something like this:

 var monthName = 'December'; var dateMonth = 31; var ele = $('<div></div>') .attr('id', 'rawr') .html(monthName + ' | ' + parseInt(dateMonth, 10)); $('#container').append(ele); 
+8
source

use the createElement function:

 var elm = document.createElement('div'); elm.setAttribute('id', 'rawr'); elm.innerHTML = THE_CODE_AND_TEXT_YOU_NEED_INSIDE_THE_DIV; 

if you want to add it to the document:

 $('MYELEMENT').append(elm); 

where MYELEMENT (obviously) is the element to which you want to add a new div.

+5
source

If you want it without jQuery, this will work like this:

 var divMonth = document.createElement('div'); divMonth.id = 'rawr'; divMonth.innerHTML = monthName + ' | ' + parseInt(dateMonth, 10); document.getElementById("where_you_want_to_put_this").appendChild(divMonth); 
+3
source

Assuming you want the html structure to be something like:

 <div id="wrapper"> ... <div id="date"> <div id="rawr"> </div> </div> </div> 

you can create html code and add content in one line:

 $("#wrapper").append('<div id="date"><div id="rawr">'+monthName+'</div> | '+parseInt(dateMonth, 10)+'</div>'); 
+2
source

I think you might be better off separating your display from your logic and updating a div or span (when you want to show inline) using jQuery. Something like the following.

<div id='rawr'> <span id='updateme'></span> </div>

<script> $("#updateme").html(monthName); </script>

0
source

Source: https://habr.com/ru/post/901454/


All Articles