So I am pulling information from google calendar and I need to divide the variables I am receiving so I can 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, as you imagine the result displayed is...
"<div id ="rawr">December</div> | 8"
It does not actually interpret the html and make the div layer. So my question is.. How can i insert html code within the variable so it actually works as html? Is there a function I am missing or is it even possible?
Thanks in advance for any help or ideas you might have!
Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.
To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.
There is absolutely no problem with storing an HTML element in a variable. You can use the return value of appendChild more to make your code more concise if you wanted, with the <li> .
href”, append the variable to it (Here we have used a variable named “XYZ”). Then we need to append the value to the URL. Now our URL is ready with the variable and its value appended to it. In the example below, we will append a variable named 'XYZ' and its value is 55.
You have this post tagged as jquery, so you could do something like so:
var monthName = 'December';
var dateMonth = 31;
var ele = $('<div></div>')
.attr('id', 'rawr')
.html(monthName + ' | ' + parseInt(dateMonth, 10));
$('#container').append(ele);
use the createElement function:
var elm = document.createElement('div');
elm.setAttribute('id', 'rawr');
elm.innerHTML = THE_CODE_AND_TEXT_YOU_NEED_INSIDE_THE_DIV;
when you want to add it to the document:
$('MYELEMENT').append(elm);
where MYELEMENT is (obviously) the element you want to append the new div to.
If you want it without jQuery something like this would work:
var divMonth = document.createElement('div');
divMonth.id = 'rawr';
divMonth.innerHTML = monthName + ' | ' + parseInt(dateMonth, 10);
document.getElementById("where_you_want_to_put_this").appendChild(divMonth);
Assuming that you want the html structure to be something like:
<div id="wrapper">
...
<div id="date">
<div id="rawr">
</div>
</div>
</div>
you can create the html code and add the content with one line:
$("#wrapper").append('<div id="date"><div id="rawr">'+monthName+'</div> | '+parseInt(dateMonth, 10)+'</div>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With