I have an array I have generated and I want to display it in html as a vertical list, preferably as each individual element.
I have done this:
var a = _.intersection(viewedUserLikedUsersArray, loggedInLikedUsersArray);
for (var i=0; i < a.length; i++){
displayListOfMatches.innerHTML = a[i];
}
but obviously this way will replace the innerHTML with the last element in the array rather than stacking each one on top of each other
You'll probably get people saying to do this:
displayListOfMatches.innerHTML = "<p>" + a.join("</p><p>") + "</p>";
...which works but note that the content of the array entries will be parsed as HTML.
If that's not okay, you can either build an HTML string by replacing those characters via map:
displayListOfMatches.innerHTML = a.map(function(entry) {
return "<p>" + entry.replace(/&/g, "&").replace(/</g, "<") + "</p>";
}).join("");
...or build the elements as you go, perhaps with forEach:
displayListOfMatches.innerHTML = ""; // You can leave this out if it's empty
a.forEach(function(entry) {
var p = document.createElement("p");
p.appendChild(document.createTextNode(entry));
displayListOfMatches.appendChild(p);
});
Of course, in all cases, you can adjust it to use different elements/markup.
Related
so I wrote a script to display 5 random arrays, but the page doesn't display anything.
here's the code:
<html>
<head>
<script>
function start(){
var arr(5),result;
result=document.getElementById("arraying");
result="<p>";
for(var i=0; i<5;i++){
arr[i]=Math.floor(Math.random()*10);
result+="arr["+i+"]= "+arr[i]+"</p><p>";
}
result+="</p>";
}
window.addEventListener("load",start,false);
</script>
</head>
<body>
<div id="arraying"></div>
</body>
</html>
I tried removing result=document.getElementById and write document.getElementById.innerHTML=result in the end of the function but didn't work. what's the error?
You cannot use the same variable for different purposes at the same time. First you assign a DOM element to result, and immediately on the next line you overwrite result with a string.
Build a string htmlStr inside your loop, and when that is done, assign this string to result.innerHTML property:
function start() {
let arr = [],
result, htmlStr = '';
result = document.getElementById("arraying");
htmlStr += "<p>";
for (let i = 0; i < 5; i++) {
arr[i] = Math.floor(Math.random() * 10);
htmlStr += "arr[" + i + "]= " + arr[i] + "</p><p>";
}
htmlStr += "</p>";
result.innerHTML = htmlStr;
}
window.addEventListener("load", start, false);
<div id="arraying"></div>
Looking at the code you seem to be missing some basic javascript concepts.
array size
This is probably your main issue:
var arr(5)
This does not make sense in javascript. Array length does not need to be predefined since all arrays are of dynamic length. Simply define an array like this:
var arr = []
Then later when you want to append new elements use push like this:
arr.push( Math.floor(Math.random()*10) )
adding html using innerHTML
There are different ways to dynamically inject html into your page. (It looks like) you tried to append the html as a string to the parent element. This is not possible.
You said you tried using innerHTML. That should work if used correctly.
A working implementation would work like this:
function start() {
var arr = []
var result = "<p>"
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) ) // Btw this array isn't actually needed.
result += "arr[" + i + "] = " + arr[i] + "</p><p>"
}
document.getElementById("arraying").innerHTML = result
}
window.addEventListener("load", start, {passive: true});
adding html using createElement
A generally better way of dynamically adding html elements is via createElement.
This way you dont have to write html and are therefore less prone for making errors. It is also more performant and easier to integrate into javascript.
I think the best explaination is a commented implementation:
function start() {
var myDiv = document.getElementById("arraying") // get parent node
var arr = []
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) )
var p = document.createElement("p") // create p element
p.innerText = "arr[" + i + "] = " + arr[i] // add text content to p element
myDiv.append(p) // append p element to parent element
}
}
window.addEventListener("load", start, {passive: true});
small tips
The let keyword works mostly the same as the var keyword, but is generally preferred because of some edge cases in which let is superior.
Fusing strings and variables using the plus operator is generally considered bad practice. A better way to do the string concatenation would have been
result += `arr[${i}] = ${arr[i]}</p><p>`
I've been struggling with converting the following C# code into something I can use in JavaScript:
var g = Model.List.GroupBy(r => Model.List.IndexOf(r) / 3).ToList();
It's use was to create the appropriate number of rows, with the appropriate number of columns within them. So for example if the list had 6 elements it would allow me to create 3 rows with 2 columns in it, this was all done in razor pages using the above GroupBy and the below code:
foreach (var parent in g)
{
#Html.Raw("<div class='row'>");
foreach (var item in parent)
{
// populate contents of row
}
#Html.Raw("</div>");
}
However for certain reasons I can't do this in Razor and need to create an alternative in JavaScript but I'm struggling to figure out a way to do this.
Primarily because I don't understand entirely how 'GroupBy' creates the list of groups and what would be a suitable alternative.
Any help, or pointing in the right direction would be great. I've tried a few solutions I found online for creating 'GroupBys' but I couldn't get them to work the way I was expecting. I also thought maybe I could split the original list into a list of dictionaries, but again had little success. I'm possibly missing something obvious.
In the end it turns out I was just missing the obvious answer, I found this excellent SO answer. I had looked at slice but couldn't quite visualise how to use it for my problem (obviously been a long day).
The post showed this snippet:
var i,j,temparray,chunk = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
temparray = array.slice(i,i+chunk);
// do whatever
}
In the end my JavaScript code looked something like this:
var listdata = await octokit.repos.listForUser({ "username": "", "type": "owner" });
var chunk = 2;
var loop = 0;
var tempArray = [];
for (var s = 0; s < listdata.data.length; s += chunk) {
tempArray[loop] = listdata.data.slice(s, s + chunk);
loop++;
}
var htmlString = "";
for (var t = 0; t < tempArray.length; t++) {
htmlString += "<div class='row'>";
var innerArray = tempArray[t];
for (var r = 0; r < innerArray.length; r++) {
var repo = innerArray[r];
htmlString +=
"<div class=\"col-md-6 col-sm-6 col-xs-12\">" +
"<div>" + repocontent + "</div>" +
"</div>"
}
htmlString += "</div>";
}
So with a list that's 6 items long, it gets split into an array that contains 3 lists of 2 items. Then I just create the html string using two for loops to create the outer bootstrap rows and the inner column classes. There's probably a more efficient way to do this but this worked a treat.
I made this helper function to assist me with stuff
function formToObject(form) {
var items = form.querySelectorAll("[name]");
var json = "{";
for (var i = 0; i < items.length; i++) {
json += '"' + items[i].name + '":"' + items[i].value + '",';
}
json = json.substring(0, json.length-1) + "}";
return JSON.parse(json);
}
There is a problem with it though, it doesn't exclude forms that are inside the form element thats passed to it. Didn't come up before but now it seems to be necessary. Is there a way to write the selector string in a way that it would exclude any children of other forms inside it?
Like "[name]:not(form *)" (which obviously doesn't work)
EDIT: got a little closer with "[name] :not(fieldset) *" but that also ignores the immediate fieldset children
When I go to print out an array, That may have items put into it at later times, like this:
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
alert(ArrayEx);
//or
document.write(ArrayEx);
It usually just prints it all out in one big blob of text. I was wondering, if I make it print in the alert box or the document, how i can make it a list, going down, or just with a , in between each one. Does anyone know how I could do that?
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
var joined = ArrayEx.join(", ");
console.log(joined);
This will log
"Zero, One, Two"
Here's a quick and simple way to loop through an array and list the items in the array:
http://jsfiddle.net/mjgbm6c3/
HTML
<ul class="sample-list"></ul>
JS
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
for(var i = 0; i < ArrayEx.length; i++){
var item = '<li>' + ArrayEx[i] + '</li>';
$('.sample-list').append(item);
}
Have a look at the Array.join() method, it will build a string out of the elements in the array and separate them with the string you pass to the separator parameter.
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
alert(ArrayEx.join(', '));
// and
document.write(ArrayEx.join(', '));
// would both output: Zero, One, Two
For a new line, replace ', ' with '\n' in alerts and '<br />' in anything going to HTML; such as document.write().
document.write(ArrayEx.join('</br>'));
I have an array with a variable amount of records. And I want to print every record of the array in the same html page. I prefer it to display in a list.
I have the following code. However this does only print the last record of the array because it overwrites the previous record in my html ul-element.
for (var i = 0; i < feedbackGeenLid.length; i++)
{
document.getElementById("feedback").innerHTML= ("<li>"+feedbackGeenLid[i] + "</li>");
}
Does anyone have an idea on how to realize this?
Your code keeps replacing the innerHTML you need to add to it.
document.getElementById("feedback").innerHTML += ("<li>"+feedbackGeenLid[i] + "</li>");
^
|
Added + here
For better performance build one string and set it to innerHTML at the end of the loop.
var out = "";
for (var i = 0; i < feedbackGeenLid.length; i++)
{
out += "<li>"+feedbackGeenLid[i] + "</li>";
}
document.getElementById("feedback").innerHTML= out;
Another option, use appendChild()
you are rewriting the content in each loop. use a variable to concatenate the content and then put it in the element:
var html = '';
for (var i = 0; i < feedbackGeenLid.length; i++)
{
html += "<li>"+feedbackGeenLid[i] + "</li>";
}
document.getElementById("feedback").innerHTML= html;