How to wrap for loop in a div? - javascript

I have been stuck on this silly thing, I can't figure out how to wrap my for loop inside of a div.
for (item = 0; item < event.length; item++) {
var ID = event[item].id;
element.find(".title").after("<span class='id'><img src='/avatar/" +ID+ "'/></span>");
}
I want to achive this:
<div>
<span></span>
<span></span>
<span></span>
</div>
Any Help is much apprciated.

Hope this snippet will be useful
// a variable for the dynamically created span
var spanString = "";
for (item = 0; item < event.length; item++) {
var ID = event[item].id;
// new string will con cat wit the spanString
spanString += ("<span class='id'><img src='/avatar/" + ID + "'/></span>");
}
// append the spanString to the `div.title`
$(".title").append($(spanString))

$(document).ready(function() {
//Assume sample event array
var event = [1, 2, 3];
for (item = 0; item < event.length; item++) {
var ID = event[item];
$("<span class='id'><img src='/avatar/" +ID+ "'/></span<br>").appendTo('#name');
};
});
Considering sample HTML Below
<div id="name">
hello
</div>
This way you can populate content inside the div

Related

JS - combining array items together in one item

For example I want to collect some tags (lets say paragraph):
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length
I loop through (iterate):
for (var i = 0; i < tagsCollectionLength; i++)
{
//get an array:
var tagsCollectionArray = tagsCollection[i];
}
Now what to do to get all array items as ONE item:
so it won't looks like:
[paragraph1, paragraph2, paragraph3]
but like:
[paragraph1paragraph2paragraph3]
I did try join. concat. etc. without success probably I'm doing something wrong, any help is appreciated. Thanks.
you can keep a variable outside the for, append the strings inside for and when for finishes, push it inside an array.
Here's how to do that -
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length;
var tags = "", tagsCollectionArray = [];
for (var i = 0; i < tagsCollectionLength; i++)
{
tags = tags + tagsCollection[i];
}
tagsCollectionArray.push(tags);
Suppose you have this html
<div>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
<p>e</p>
</div>
Assuming the result you want is an Array of all the paragraphs's content ([paragraph1paragraph2paragraph3]), then you could do the following:
tagsCollection = document.getElementsByTagName('p');
var ar = [];
for(var i = 0; i < tagsCollection.length; i++ ) {
ar.push(tagsCollection[i].innerText)
}
console.log([ar.join('')]) // => ["abcde"]
See this fiddle
As I have already commented, you can use Array.join("").
JSFiddle.
(function() {
var data = [];
var str = [].map.call(document.getElementsByTagName('p'), function(item) {
return item.innerHTML;
}).join("");
data.push(str);
document.write("<pre>" + JSON.stringify(data) + "</pre>");
})()
<p>hello</p>
<p>workd</p>
<p>test</p>

For loop through Array only shows last value

I'm trying to loop through an Array which then uses innerHTML to create a new element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.
window.onload = function() {
// Read value from storage, or empty array
var names = JSON.parse(localStorage.getItem('locname') || "[]");
var i = 0;
n = (names.length);
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
}
I have a UL with the id 'list' in my HTML.
Change your for loop:
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
Use += instead of =. Other than that, your code looks fine.
I suggest you to first make a div by create element. there you add your innerHTML and after that you can do the appendchild. That will work perfectly for this type of scenario.
function displayCountries(countries) {
const countriesDiv = document.getElementById('countriesDiv');
countries.forEach(country => {
console.log(country.borders);
const div = document.createElement('div');
div.classList.add('countryStyle');
div.innerHTML = `
<h1> Name : ${country.name.official} </h1>
<h2> Capital : ${country.capital} </h2>
<h3> Borders : ${country.borders} </h3>
<img src="${country.flags.png}">
`;
countriesDiv.appendChild(div);
});
}

How to increment div id value?

I have got a task to set the menu as selected. For that I use dynamic id.
So I want to increment it with respect to the selection
My code is
<div class="menuHeader ui-corner-top" id="menu"+ i>
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top" id="menu"+ i>
<span>New Transaction</span>
</div>
<div class="menuHeader ui-corner-top" id="menu"+ i>
<span>Portfolio</span>
</div>
javascript is
$(document).ready(function () {
alert(document.URL);
var list = $("#menu");
for (var i = 1; i <= list.length; i++) {
list[i].innerHTML = i;
}
var str = document.URL.toLowerCase().indexOf("portfolio/index");
alert(str);
if (str >= 0) {
$('#menu').addClass("menuHeaderActive");
}
});
How can I do this?
var i=0;
$('.menuHeader').each(function(){
i++;
var newID='menu'+i;
$(this).attr('id',newID);
$(this).val(i);
});
This is the way to do it with Jquery
val elementList = $(".menu");
for (var i = 1; i <= list.length; i++) {
elementList[i].attr("id", "menu" + i);
}
Just use a class name instead of an id, you will be able to reuse the code you have just added but in this way.
var list = $(".menu");
One advice, don't do the highlighting of the item menu with javascript, do it server-side, and you can add the "activating" class directly in the HTML of the LI.

How to point elements childrens with JavaScript

I have little problem with element childrens.
Heres some code to explain my question:
function check(element){
// I want to get custom attribute from element children.
// Children elements are always radio buttons
var temp = element. ?? .attr('temp');
return temp;
}
// element variable is the whole div here
<div id = "test">
<table>
<tr>
<td> <input type="radio" temp="somethinghere"/></td>
</tr>
</table>
</div>
Hope someone has ideas or even better.. solution.
I think you want something like this:
function check(element) {
var ret = [];
for (var i = 0; i < element.childNodes.length; i++) {
if (element.childNodes[i].type == 'radio') {
ret.push(element.childNodes[i].getAttribute('temp'));
}
}
return ret;
}
This will return an array containing all the temp attributes of the radio children of the element.
var temp = element.getAttribute('temp')
Or
var temp = element.temp = temp;
Or
var temp = element['temp'] = temp;
https://developer.mozilla.org/en/DOM/element.getAttribute
Edit: try:
var temp = '';
for (var i = 0; i < element.childNodes; i++)
temp += element.childNodes[i].getAttribute('temp');
return temp;
Is this what you're looking for?
To get an array of all the children of element :
element.childNodes;
To get an array of all input tags that are descendants of element :
element.getElementsByTagName("input")
Then loop through either of those arrays.
try this for the first child radio button
var temp = element.children(':radio:first').attr('temp');
of if you want all 'temp' attr from all child radio button do following:
var arrTemp = element.children(':radio').map(function(){
return $(this).attr('temp');
// or you can make it more detail like:
// return { ID: $(this).attr('id'), Temp: $(this).attr('temp') };
}).get();
UPDATE for table sample
var arrTemp = element.find(':radio').map(function(){
return $(this).attr('temp');
// or you can make it more detail like:
// return { ID: $(this).attr('id'), Temp: $(this).attr('temp') };
}).get();

Append an Array to an Unordered List

What I'm trying to accomplish with this code is to output the array alphabet as a series of list items into an existing unordered list in the actual markup. I've got the array into list items, but I can't figure out how to tell it to append itself to an existing unordered list <ul id="itemList"></ul>.
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
document.write('<li>' + alphabet[indexNum++] + '</li>');
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
Don't use document.write to do it. You should act like this:
function write_letters(){
var letters = "";
for (var i = 0; i < alphabet.length; i++ ) {
//Also I don't understand the purpose of the indexNum variable.
//letters += "<li>" + alphabet[indexNum++] + "</li>";
letters += "<li>" + alphabet[i] + "</li>";
}
document.getElementById("itemList").innerHTML = letters;
}
More proper way is to use DOM (in case you want full control of what's coming on):
function write_letters(){
var items = document.getElementById("itemList");
for (var i = 0; i < alphabet.length; i++ ) {
var item = document.createElement("li");
item.innerHTML = alphabet[i];
items.appendChild(item);
}
}
You can use a combination of createElement() and appendChild() to add new HTML elements within another HTML element. The code below should work for you:
<html>
<head>
<title>Script Test</title>
</head>
<body>
<ul id="itemList"></ul>
</body>
<script>
var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
var myElement;
function write_letters(){
for (i = 0; i < alphabet.length; i++ ) {
// Create the <LI> element
myElement = document.createElement("LI");
// Add the letter between the <LI> tags
myElement.innerHTML = alphabet[indexNum++];
// Append the <LI> to the bottom of the <UL> element
unorderedList.appendChild(myElement);
}
}
if (itemsExist){
write_letters();
} else {
document.write("error!");
}
</script>
</html>
Note how the script exists below the body tag. This is important if you want your script to work the way you wrote it. Otherwise document.getElementById('itemList') will not find the 'itemList' ID.
Try to reduce the actions on the DOM as much as possible. Every appendChild on unorderedList forces the browser to re-render the complete page. Use documentFragement for that sort of action.
var frag = document.createDocumentFragment();
for (var i = alphabet.length; i--; ) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(alphabet[indexNum++]));
frag.appendChild(li);
}
unorderedList.appendChild(frag);
So there will be only one DOM action which forces a complete redraw instead of alphabet.length redraws

Categories

Resources