I have an assignment for school where we have to make random edits to a webpage using only javascript, no jquery or css is allowed for the edits. I'm looking to reverse the order of the nav bar, for example change
home about contact
to
contact about home
because they are links I had to change the href as well, but I have made a silly mistake somewhere because it is changing everything to home (the the text to "home" and the href to the href i want to use for "home") so I think the problem must be my second for loop or else in the loop, I just can't see where, so any help would be much appreciated!
var navIds = ["hHome", "hAbout", "hPlants", "hGarden", "hNews", "hArticle", "hContact"];
var navHref = ["index.html", "about.html", "plants.html", "garden.html", "news.html", "article.html", "contact.html"];
var navText = ["home", "about", "plants", "garden", "news", "article", "contact"];
function changeNav()
{
for(var i=0; i<navIds.length; i++)
{
for(var j=navHref.length; j>=0; j= j-1)
{
var x = document.getElementById(navIds[i]);
var y = navHref[j];
x.setAttribute("href", y);
x.textContent = navText[j];
}
}
}
the vars are just arrays where i stored the ids for what i want to change and the hrefs i want to use and the text i want them to display.
thanks in advance if you can help!!
the html is just a from a free template and isn't mine bar adding an id to the links,
<div id="header">
<img src="images/logo.png" alt="Logo">
<ul>
<li>
<a id="hHome" href="index.html">Home</a>
</li>
<li>
<a id="hAbout" href="about.html">About</a>
</li>
<li>
<a id="hPlants" href="plants.html">Plants</a>
</li>
<li>
<a id="hGarden" href="gardens.html">Gardens</a>
</li>
<li class="current">
<a id="hNews" href="news.html">News</a>
<ul>
<li class="current">
<a id="hArticle" href="article.html">Article</a>
</li>
</ul>
</li>
<li>
<a id="hContact" href="contact.html">Contact</a>
</li>
</ul>
</div>
<div id="partA">
<input type="submit" value="PartA" onclick="linkA()"/>
<input type="submit" value="PartB" onclick="linkB()"/>
</div>
You can handle that in one single for-loop..
Maybe you should have a look on the For-In Loop -> https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for...in
Heres what i come up with:
for(navs in navIds){
var html = '<a id="' + navIds[navs] + '" href="' + navHref[navs] + '">' + navText[navs] + '</a>';
document.body.insertAdjacentHTML('afterend',html);
}
You can try it here: http://jsfiddle.net/1tLkz9o2/
As promised, here is how I would approach this problem.
First, condense the multiple arrays into a single array containing nav objects.
var navElementData = [
{ id: "hHome" , href: "index.html" , text: "home" },
{ id: "hAbout" , href: "about.html" , text: "about" },
{ id: "hPlants" , href: "plants.html" , text: "plants" },
{ id: "hGarden" , href: "garden.html" , text: "garden" },
{ id: "hNews" , href: "news.html" , text: "news" },
{ id: "hArticle", href: "article.html", text: "article" },
{ id: "hContact", href: "contact.html", text: "contact" }
];
This way, it is clear that each object in the array relates to a single menu item and makes the reversal process easier.
Below I've provided the full working implementation that I will reference.
We now need a function that will actually do the rendering of a single element. I've named it getNavElement.
To render these elements to the document, I've created a new generic function named renderNav that takes in a container (e.g. a div), and some data navElementData.
Finally, I've created a simple function that wraps this renderNav function named renderReverseNav that simply reverses the data before calling renderNav.
You can view the working example below. Let me know if you have any questions.
http://jsbin.com/molimawicu/1/edit?html,js,output
// Create a new nav element
function getNavElement(id, href, text) {
var element = document.createElement('a');
element.id = id;
element.href = href;
element.textContent = text;
element.setAttribute('style', 'margin: 5px');
return element;
}
// Render the nav element
function renderNav(container, navElementData) {
// Clear the existing container
container.innerHTML = '';
// Map over the data given
navElementData.map(function(data) {
// Create a new element
var element = getNavElement(data.id, data.href, data.text);
// Append it to the container
container.appendChild(element);
});
}
function renderReverseNav(container, navElementData) {
return renderNav(container, navElementData.reverse());
}
// --- usage ---
var navElementData = [
{ id: "hHome" , href: "index.html" , text: "home" },
{ id: "hAbout" , href: "about.html" , text: "about" },
{ id: "hPlants" , href: "plants.html" , text: "plants" },
{ id: "hGarden" , href: "garden.html" , text: "garden" },
{ id: "hNews" , href: "news.html" , text: "news" },
{ id: "hArticle", href: "article.html", text: "article" },
{ id: "hContact", href: "contact.html", text: "contact" }
];
var navContainer = document.getElementById('navContainer');
var revNavContainer = document.getElementById('revNavContainer');
renderNav(navContainer, navElementData);
renderReverseNav(revNavContainer, navElementData);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="navContainer"></div>
<div id="revNavContainer"></div>
</body>
</html>
Related
I'm looping through all the html tags in an html-file, checking if those tags match conditions, and trying to compose a JSON-object of a following schema:
[
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' },
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' },
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' }
]
But I'd like to create the new entry only for elements, classed "header", all the other elements have to be added to earlier created entry. How do I achieve that?
Current code:
$('*').each((index, element) => {
if ( $(element).hasClass( "header" ) ) {
jsonObject.push({
title: $(element).text()
});
};
if( $(element).hasClass( "date" )) {
jsonObject.push({
date: $(element).text()
});
}
//links.push($(element))
});
console.log(jsonObject)
Result is:
{
title: 'TestA'
},
{ date: '10.10.10' },
{
title: 'TestB'
},
{ date: '10.10.11' }
I'd like it to be at this stage something like:
{
title: 'TestA'
,
date: '10.10.10' },
{
title: 'TestB'
,
date: '10.10.11' }
UPD:
Here's the example of HTML file:
<h1 class="header">H1_Header</h1>
<h2 class="date">Date</h2>
<p>A.</p>
<p>B.</p>
<p>С.</p>
<p>D.</p>
<a class="source">http://</a>
<h1 class="header">H1_Header2</h1>
<h2 class="date">Date2</h2>
<p>A2.</p>
<p>B2.</p>
<p>С2.</p>
<p>D2.</p>
<a class="source">http://2</a>
Thank you for your time!
Based on your example Html, it appears everything you are trying to collect is in a linear order, so you get a title, date, body and link then a new header with the associated items you want to collect, since this appears to not have the complication of having things being ordered in a non-linear fasion, you could do something like the following:
let jsonObject = null;
let newObject = false;
let appendParagraph = false;
let jObjects = [];
$('*').each((index, element) => {
if ($(element).hasClass("header")) {
//If newObject is true, push object into array
if(newObject)
jObjects.push(jsonObject);
//Reset the json object variable to an empty object
jsonObject = {};
//Reset the paragraph append boolean
appendParagraph = false;
//Set the header property
jsonObject.header = $(element).text();
//Set the boolean so on the next encounter of header tag the jsobObject is pushed into the array
newObject = true;
};
if( $(element).hasClass( "date" )) {
jsonObject.date = $(element).text();
}
if( $(element).prop("tagName") === "P") {
//If you are storing paragraph as one string value
//Otherwise switch the body var to an array and push instead of append
if(!appendParagraph){ //Use boolean to know if this is the first p element of object
jsonObject.body = $(element).text();
appendParagraph = true; //Set boolean to true to append on next p and subsequent p elements
} else {
jsonObject.body += (", " + $(element).text()); //append to the body
}
}
//Add the href property
if( $(element).hasClass("source")) {
//edit to do what you wanted here, based on your comment:
jsonObject.link = $(element).next().html();
//jsonObject.href= $(element).attr('href');
}
});
//Push final object into array
jObjects.push(jsonObject);
console.log(jObjects);
Here is a jsfiddle for this: https://jsfiddle.net/Lyojx85e/
I can't get the text of the anchor tags on the fiddle (I believe because nested anchor tags are not valid and will be parsed as seperate anchor tags by the browser), but the code provided should work in a real world example. If .text() doesn't work you can switch it to .html() on the link, I was confused on what you are trying to get on this one, so I updated the answer to get the href attribute of the link as it appears that is what you want. The thing is that the anchor with the class doesn't have an href attribute, so I'll leave it to you to fix that part for yourself, but this answer should give you what you need.
$('*').each((index, element) => {
var obj = {};
if ( $(element).hasClass( "header" ) ) {
obj.title = $(element).text();
};
if( $(element).hasClass( "date" )) {
obj.date = $(element).text()
}
jsonObject.push(obj);
});
I don't know about jQuery, but with JavaScript you can do with something like this.
const arr = [];
document.querySelectorAll("li").forEach((elem) => {
const obj = {};
const title = elem.querySelector("h2");
const date = elem.querySelector("date");
if (title) obj["title"] = title.textContent;
if (date) obj["date"] = date.textContent;
arr.push(obj);
});
console.log(arr);
<ul>
<li>
<h2>A</h2>
<date>1</date>
</li>
<li>
<h2>B</h2>
</li>
<li>
<date>3</date>
</li>
</ul>
Always use map for things like this. This should look something like:
let objects = $('.header').get().map(el => {
return {
date: $(el).attr('date'),
title: $(el).attr('title'),
}
})
I have some HTML in my DOM and I want to replace some strings in it, but only if that was not already replaced or that is not a TAG.
All that is based on an Array that contains the string I want to find and the new string I want this to be replace with.
Work in progress: https://jsfiddle.net/u2Lyaab1/23/
UPDATE: The HTML markup is just for simplicity written with ULs in the sample code, BUT it can contain different tags, event different nesting levels
Basically the desiredReplcement works nice (except that it looks in tags too), but I want that to happen on the DOM, not the new string because I want to maintain any other HTML markup in the DOM.
SNIPPET:
var list = [{
original: 'This is',
new: 'New this is'
},
{
original: 'A list',
new: 'New A list'
},
{
original: 'And I want',
new: 'New And I want'
},
{
original: 'To wrap',
new: 'New To wrap'
},
{
original: 'li',
new: 'bold'
},
{
original: 'This',
new: 'New This'
},
{
original: 'strong',
new: 'bold'
}, {
original: 'This is another random tag',
new: 'This is another random tag that should be bold'
}
];
var div = $('.wrap');
var htmlString = div.html();
var index = 0;
list.forEach(function(item, index) {
console.log(index + ' Should replace: "' + item.original + '" with "' + item.new + '"');
//I know that there is something here, but not sure what
index = htmlString.indexOf(item.original);
var expressionLength = index + item.original.length;
var substring = htmlString.substring(index, expressionLength);
var desiredReplcement = substring.replace(item.original, '<strong>' + item.new + '</strong>');
console.log('index', index);
console.log('substring', substring);
console.log('desiredReplcement', desiredReplcement);
//Current implementation in replace looks in the full div, but I just want to replace in the substring mathced above;
var replacement = '<strong>' + item.new + '</strong>';
var newHTML = div.html().replace(item.original, replacement);
div.html(newHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<ul>
<li>This is</li>
<li>A list</li>
<li>And I want</li>
<li>This should not be bold</li>
<li>To wrap</li>
<li>This</li>
<li>strong</li>
<li>li</li>
</ul>
<span><p><em>This is another random tag</em></p></span>
</div>
Your div variable is referencing <div class="wrap">...</div>, therefore your htmlString value is a group of html tags instead of string.
That is the main reason your code is not working as expected.
And therefore I rewrote your implementation.
var list = [
{
original: 'This is',
new: 'New this is'
},
{
original: 'A list',
new: 'New A list'
},
{
original: 'And I want',
new: 'New And I want'
},
{
original: 'To wrap',
new: 'New To wrap'
},
{
original: 'li',
new: 'bold'
},
{
original: 'This',
new: 'New This'
},
{
original: 'strong',
new: 'bold'
}
];
var div = document.getElementsByClassName('wrap')[0].getElementsByTagName('li'); // Getting all <li> elements within <div class="wrap">
Array.prototype.forEach.call(div, function(li, x){ // Borrowing Array's forEach method to be used on HTMLCollection
list.forEach(function(value, i){ // Looping through list
if (value.original === li.innerHTML) // if list[i]['original'] === li[x].innerHTML
li.innerHTML = '<strong>' + value.new + '</strong>';
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<ul>
<li>This is</li>
<li>A list</li>
<li>And I want</li>
<li>This should not be bold</li>
<li>To wrap</li>
<li>This</li>
<li>strong</li>
<li>li</li>
</ul>
</div>
I don't think that jQuery is necessary here.
First, you want to retrieve your container, which in your case will be the .wrap div.
var container = document.querySelector('.wrap');
Then you want to create a recursive function that will loop through an array to search and replace the data provided.
function replacement(containers, data){
if(!data || !data.length)
return;
for(let i=0; i<containers.length; i++){
var container = containers[i];
// Trigger the recursion on the childrens of the current container
if(container.children.length)
replacement(container.children, data);
// Perform the replacement on the actual container
for(let j=0; j<data.length; j++){
var index = container.textContent.indexOf(data[j].original);
// Data not found
if(index === -1)
continue;
// Remove the data from the list
var replace = data.splice(j, 1)[0];
container.innerHTML = container.innerHTML.replace(replace.original, '<strong>' + replace.new + '</strong>');
// Lower the j by 1 since the data array length has been updated
j--;
// Only want to perform one rule
break;
}
}
}
Demo: https://jsfiddle.net/u2Lyaab1/25/
The following code will not replace tags and will do only one replacement for one text node (if there is any match). It looks through the whole structure in a recursive manner and checks the text of the elements.(and it uses the same list you described in your question)
Requirements:
Replace text just in case of exact match => use === instead of indexOf
Replace text only once => remove item from list after use
var div = $('.wrap');
function substitute(htmlElement, substituteStrings){
var childrenElements = htmlElement.children;
if(childrenElements.length !== 0){
for (let i=0;i<childrenElements.length;i++){
substitute(childrenElements[i], substituteStrings);
}
} else {
var htmlString = htmlElement.innerText;
substituteStrings.some(function(item){
if(htmlString == item.original){
htmlElement.innerHTML = htmlString.replace(item.original, '<strong>' + item.new + '</strong>');
substituteStrings.splice(index,1);
return true;
}
});
}
}
substitute(div[0],list);
The basic idea is to use recursion to search through every nested node in the parent node.
My answer (partial answer) has the same results as Zsolt V's, but is a little less elegant.
Zsolt V has checked child nodes, and it can therefore work with innerHTML by using HTML tags. I on the other hand have checked if a node is a textNode, and have built the replacement nodes using the DOM (pure DOM solution) and nodes' textContent property.
var list = [{
original: 'This is',
new: 'New this is'
}, {
original: 'A list',
new: 'New A list'
}, {
original: 'And I want',
new: 'New And I want'
}, {
original: 'To wrap',
new: 'New To wrap'
}, {
original: 'li',
new: 'bold'
}, {
original: 'This',
new: 'New This'
}, {
original: 'strong',
new: 'bold'
}, {
original: 'This is another random tag',
new: 'This is another random tag that should be bold'
}
];
//I want for each expression in this array, to find that expression in array, replace-it and make-it bold with a <strong> tag.
var div = document.getElementsByClassName("wrap")[0];
function processNode(node) {
if (node.nodeName === "#text") {
list.forEach(function(item, index) {
if (node.parentNode && node.textContent.indexOf(item.original) > -1) {
//node.textContent = node.textContent.replace(item.original, item.new);
let untouched = node.textContent.split(item.original);
console.log(untouched);
for (let i = untouched.length - 1; i > 0; i--) {
untouched.splice(i, 0, item.new);
}
console.log(untouched);
for (let i = 0, l = untouched.length; i < l; i++) {
let newNode = i % 2 === 0 ? document.createTextNode("") : document.createElement("strong");
newNode.textContent = untouched[i];
node.parentNode.appendChild(newNode);
}
node.parentNode.removeChild(node);
}
})
} else {
node.childNodes.forEach(function(child, index) {
processNode(child);
})
}
}
processNode(div)
JSFiddle (partial answer)
You write in the comments on Zsolt V's answer that:
but as you can see, the last sentence is replaced differently than the expected in the list
However, the problem is not with the code, but with the ordering of the list array. The problem is that you have replacements that work within one another, i.e. acting on list[7], with list[0]:
"This is another random tag" (list[7] before)
-> "New this is another random tag" (list[7] after applying changes from list[0])
You need to be mindful of the ordering.
In fact, I moved the last item in the list array to the top, and the results are as you've asked for.
var list = [{
original: 'This is another random tag',
new: 'This is another random tag that should be bold'
}, {
original: 'This is',
new: 'New this is'
}, {
original: 'A list',
new: 'New A list'
}, {
original: 'And I want',
new: 'New And I want'
}, {
original: 'To wrap',
new: 'New To wrap'
}, {
original: 'li',
new: 'bold'
}, {
original: 'This',
new: 'New This'
}, {
original: 'strong',
new: 'bold'
}
];
JSFiddle (full answer)
I am attempting to append some li elements inside a ul. In this scenario, I am looping through the array called blogData and accessing each tags method. The issue I am having- I can't seem to loop through each array inside tags and appending data to the ul inside each article appends all tags data from each object to each ul.
const blogData = [
{
title : "blog first",
date : "01",
tags : ["first", "second"],
body : "Some text",
id : 1
},
{
title : "blog second",
date : "02",
tags : ["third", "fourth"],
body : "Some more text",
id : 2
}
];
function tagUl (object) {
setTimeout(() => {
const ul = $('.tags-ul');
for (let i = 0; i < ul.length; i++) {
const $li = $('<li>');
$li.text(object[i].tags);
ul.append($li); }
}, 10);
}
tagUl(blogData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article>
<ul class="tags-ul">
</ul>
</article>
<article>
<ul class="tags-ul">
</ul>
</article>
As you can see here by running the code all ul tags get the same li's appended to them. As the title says it returns [object Object]. This was the case a few minutes ago when I was first writing this. The case now is that it simply returns the wrong data
Your problem is that your ul variables represents all the <ul class="tags-ul"> elements, and so doing an "append" on that variable appends the same content to all the elements it represents.
You can access each element separately, either by looping, or more crudely (since you already have a for loop to go through your blogData object), by getting the raw element from the jQuery object by its index, and then appending specifically to that. It also creates a separate <li> for each tag by looping through the tags array itself.
const blogData = [{
title: "blog first",
date: "01",
tags: ["first", "second"],
body: "Some text",
id: 1
},
{
title: "blog second",
date: "02",
tags: ["third", "fourth"],
body: "Some more text",
id: 2
}
];
function tagUl(object) {
const ul = $('.tags-ul');
for (let i = 0; i < ul.length; i++) {
const $li = $('<li>');
for (var j = 0; j < object[i].tags.length; j++) {
$(ul[i]).append($("<li/>", { text: object[i].tags[j] }));
}
}
}
$(function() {
tagUl(blogData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article>
<ul class="tags-ul">
</ul>
</article>
<article>
<ul class="tags-ul">
</ul>
</article>
P.S. I assumed your setTimeout was a kludge to allow the HTML content to load before you run the code, so I replaced it with a more reliable jQuery wrapper which waits for the document to be ready before executing any code within it ($(function() { ... }); is a shorthand for the slightly more comprehensible statement $(document).ready(function() ... });)
you need to iterate tags array inside each object in blogData and then add li for each value inside the array. something like this will work:
const blogData = [
{
title : "blog first",
date : "01",
tags : ["first", "second"],
body : "Some text",
id : 1
},
{
title : "blog second",
date : "02",
tags : ["third", "fourth"],
body : "Some more text",
id : 2
}
];
function tagUl (object) {
setTimeout(() => {
const ul = $('.tags-ul');
for (let i = 0; i < ul.length; i++) {
var tags = object[i].tags;
for (var j=0; j<tags.length; j++){
$(ul[i]).append("<li>" + tags[j] + "</li>");
}
}
}, 10);
}
tagUl(blogData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article>
<ul class="tags-ul">
</ul>
</article>
<article>
<ul class="tags-ul">
</ul>
</article>
I have this javascrpt code:
for (var data in feature.data) {
if (!shownParameters[data]) continue;
var xmlString = "<a href='www.cnn.com'>Link</a>"
var elem = $.parseHTML(xmlString);
var item = $("<li>", { style: 'padding:0px;text-align:right' })
.append($('<div>')
.append($("<span>", { text: elem }).addClass("view"))
.addClass("feature-data-value"))
.append($("<div>").addClass("clear-div"));
item.appendTo('#wfs-details-list');
}
In code above I try want to create anchor link DOM element.
But in the view I get this:
Here how it looks in the view:
Any idea why I cant create in the DOM anchor link elelment?
actually, this is not true way, but resolve your issue..
for (var data in feature.data) {
if (!shownParameters[data]) continue;
var xmlString = "<a href='http://www.cnn.com'>Link</a>";
var item = $("<li>", {style: 'padding:0px;text-align:right'})
.append($('<div>').append($("<span>").append(xmlString)).addClass("view"))
.addClass("feature-data-value")
.append($("<div>").addClass("clear-div"));
item.appendTo('#wfs-details-list');
}
If you are aiming to create this:
<ul id="wfs-details-list">
<li style="padding:0px;text-align:right" class="feature-data-value">
<div class="view"><span>Link</span>
</div>
<div class="clear-div"></div>
</li>
</ul>
then this is clearer but not shorter
for (var data in feature.data) {
if (!shownParameters[data]) continue;
$("<li>", {
style: 'padding:0px;text-align:right', // belongs in a class
class: "feature-data-value"
})
.append(
$('<div>', {
class: "view"
})
.append(
$("<span/>").append(
$("<a/>", {
href: "http://www.cnn.com",
text: "Link"
})
)
)
)
.append($("<div/>", {
class: "clear-div"
}))
.appendTo('#wfs-details-list');
}
I'm gonna append comments into <ul class="chat" id="comments_section"> with retrieved remote json data
return json data like this :
rtndata = [
{
username: Jordan,
message: 123,
},
{
username: Kobe,
message: 456,
},
]
implement ideas :
rtndata.forEach(function (comment, index) {
if index == EvenNumber:
append_comment_div_with_Even_Number_format;
else :
append_comment_div_with_Odd_Number_format;
});
Finnaly the DOM structure should look like the following,
The attributes left and right should be used interleavely in the comment div template.
Could we use any template technique in purely js lib? (Does any one lib of backbone.js, react.js, underscore.js can do this job elegantly ?)
Thank you.
Expected result
<ul class="chat" id="comments_section">
<li class="left.clearfix">
<span class="pull-left chat-img">
<img src="http://graph.facebook.com/Jordan/picture">
</span>
<span class="pull-left msg">
123
</span>
</li>
<li class="right.clearfix">
<span class="pull-right chat-img">
<img src="http://graph.facebook.com/Kobe/picture">
</span>
<span class="pull-right msg">
456
</span>
</li>
</ul>
By the looks of it, you're trying to adjust the style of alternate elements by adding css classes via js.
You can handle this without js, using css :nth-child selector:
li:nth-child(odd) {
}
li:nth-child(odd) span.msg{
}
li:nth-child(even) {
}
li:nth-child(even) span.msg{
}
If you must add classes (maybe you're using bootstrap), you should be able to do something like the following using underscore's template method:
<ul class="chat" id="comments_section">
<% _.each(comments, function(comment, i) { %>
<li class="<%= i%2==0? 'left' : 'right' %> clearfix">
<span class="pull-<%= i%2==0? 'left' : 'right' %> chat-img">
<img src="http://graph.facebook.com/Kobe/picture">
</span>
<span class="pull-<%= i%2==0? 'left' : 'right' %> msg">
456
</span>
</li>
<% }); %>
</ul>
Here's one approach:
var rtndata = [{
username: 'Jordan',
message: 123,
}, {
username: 'Kobe',
message: 456,
}, ];
var ul = document.getElementById('comments_section');
rtndata.forEach(function(comment, index) {
var even = (index % 2 === 0);
var li = document.createElement('li');
li.className = (even ? 'left.clearfix' : 'right.clearfix');
var span1 = document.createElement('span');
span1.className = (even ? 'pull-left' : 'pull-right') + ' chat-img';
var img = document.createElement('img');
img.src = 'http://graph.facebook.com/' + comment.username + '/picture';
var span2 = document.createElement('span');
span2.className = (even ? 'pull-left' : 'pull-right') + ' msg';
span2.innerHTML = comment.message;
span1.appendChild(img);
li.appendChild(span1);
li.appendChild(span2);
ul.appendChild(li);
});
Output:
Since you don't have that many elements, we can create a few elements and set them. If you have a lot, a second approach would be to create an html template and do a find replace.