Labelling multiple elements using loops - javascript

I am currently trying to loop through multiple input boxes using loops but I don't know how to go about doing it.
My JS code:
function tagger() {
var t;
for (t = 0; t < 5; t++) {
document.getElementsByClassName("pl")[0].getElementsByTagName("input")
}
};
return tagger();
HTML:
<h1 class="pizza">Pineapple</h1>
<body class="maco">
<div class="keys">
<span class="press" onclick="car()"><i class="fas fa-fingerprint"></i><h2>Log In</h2></span>
<span class="type" id="heyu"><input class="entry" placeholder="Password"></span>
</div>
</body>
</html>
Thanks in advance for any help rendered!

You must to add the t variable as index of (getElementsByTagName)
document.getElementsByClassName("pl")[0].getElementsByTagName("input")[t];
or you can use forEach Method is the best way for looping trough arrays
function tragger () {
var _Element = Array.from(document.querySelector("pl input"));
_Element.forEach(function (ele) {
//do some code for each input
ele.value = 'etc';
});
}
tragger();

Related

How do I use For Loop in JavaScript to show the list?

I am a beginner in JavaScript and I can't figure out the following problem: I am trying to create a simple JavaScript Movie List. I have 10 lists on the Movie List. I tried to show all of the lists with for loop, but it doesn't work.
Here's the code:
function renderModal() {
for (let i = 0; i < listMovies.length; i++) {
let movieData = listMovies[i];
document.getElementById("poster").src = movieData.img;
document.getElementById("title").innerHTML = movieData.name;
document.getElementById("genre").innerHTML = movieData.genre;
document.getElementById("rating-num").innerHTML = "Rating: "+ movieData.rating + "/10";
document.getElementById("movie-desc").innerHTML = movieData.desc;
document.getElementById("imdb-page").href = movieData.link;
return movieData;
}
}
What do I have to do?
Help me to fix it!.
You can use template tag for list and render it into target element.I am showing an example.
Movie list
<div id="movieList"></div>
template for list
<template id="movieListTemplate">
<div class="movie">
<img src="" class="poster" alt="">
<div class="title"></div>
<div class="genre"></div>
<div class="rating-num"></div>
<div class="movie-desc"></div>
<div class="imdb-page"></div>
</div>
</template>
Javascript code:
if (listMovies.length > 0) {
const movileListTemplate = document.getElementById('movieListTemplate')
const movieRenederElement = document.getElementById('movieList')
for(const movie of listMovies) {
const movieEl = document.importNode(movileListTemplate.content, true)
movieEl.querySelector('.poster').src = movie.img
movieEl.querySelector('.title').textContent = movie.name
//use all queryselector like above
}
}
Your return movieData; will stop the loop dead. Not that running it more than once will change anything since you change the same elements over and over. IDs must be unique.
Here is a useful way to render an array
document.getElementById("container").innerHTML = listMovies.map(movieData => `<img src="${movieData.img}" />
<h3>${movieData.name}</h3>
<p>${movieData.genre}</p>
<p>Rating: ${movieData.rating}/10</p>
<p>${movieData.desc}
IMDB
</p>`).join("<hr/>");
With return movieData, the for loop will ends in advance.You should put it outside the for loop.

Including the current node in the find scope

Consider the following snippet as an example:
<div class="bar foo">
</div>
<div class="bar">
<div class="foo"></div>
</div>
Given var $set=$('.bar'); I need to select both nodes with foo class. What is the proper way to achieve this. Considering addBack() requires a selector and here we need to use the $set jQuery object and $set.find('.foo') does not select the first node.
use this :
var $set = $(".bar").filters(function () {
var $this = $(this);
if($this.is(".foo") || $this.find(" > .foo").length !== 0){
return true;
} else{
return false;
}
});
Here's one way of going about it:
var set = $('.bar');
var foos = [];
for (var i = 0; i < set.length; i++) {
if ($(set[i]).hasClass('foo')) {
foos.push(set[i]);
}
}
if (set.find('.foo').length !== 0) {
foos.push(set.find('.foo')[0]);
}
console.log(foos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bar foo"></div>
<div class="bar">
<div class="foo"></div>
</div>
The for loop checks all elements picked up with jQuery's $('.bar'), and checks if they also have the foo class. If so, it appends them to the array. The if checks if any of the elements picked up in set have any children that have the foo class, and also adds them.
This creates an array that contains both of the DIVs with the foo class, while excluding the one with just bar.
Hope this helps :)
test this :
var $newSet = $set.filter(".foo").add($set.has(".foo"));
You could use the addBack() function
var $set=$('.bar');
console.log($set.find(".foo").addBack(".foo"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bar foo">
</div>
<div class="bar">
<div class="foo"></div>
</div>

Loop in jquery based on razor loop

I have a for each loop in my razor view (MVC4)
#foreach (var fe in ViewBag.FeatureProducts)
{
<div class="product-details" style="display:none;">#Html.Raw(fe.Details)</div>
<div class="product-qty-dt"> </div>
}
in the each loop i have to extract the #html row content and display in to the div 'product-qty-dt'.
For that I write the following jquery,
$(document).ready(function () {
var data = $('.product-details p').map(function () {
return $(this).text();
}).get();
//product availability
var availability = data[2].split(",");
$.each(availability, function (i) {
$('.product-qty-dt').append( availability[i])
});
});
But this was only consider the last foreach raw. how can i call this jquery in each loop call.
For example, In first loop,
<div class="product-details" style="display:none;"><p>Lorem, Ispum</p><p>doler emit,fghjh</p><p>9gm</p></div>
<div class="product-qty-dt"> 9gm </div>
second loop
<div class="product-details" style="display:none;"><p>Lorem, Ispum</p><p>doler emit,fghjh</p><p>5gm</p></div>
<div class="product-qty-dt"> 5gm </div>
Thirdloop
<div class="product-details" style="display:none;"><p>Lorem, Ispum</p><p>doler emit,fghjh</p><p>3gm</p></div>
<div class="product-qty-dt"> 3gm </div>
The following will add the text of the last <p> in a <div class="product-details"> element into the corresponding <div class="product-qty-dt"> element
$('.product-details').each(function () {
var t = $(this).children('p').last().text();
$(this).next('.product-qty-dt').text(t);
})
This should do the trick. Also the data array is still used just incase you would like to access other data portions stored in product-details.
$(".product-details").each(function()
{
var data = $(this).find('p').map(function () { return $(this).text() }).get();
$(this).next('.product-qty-dt').text(data[2]);
})

I'm looping over an array and modifying the contents of the array, but I don't get the results I expect.

I'm looping over an array and modifying the contents of the array, but I don't get the results I expect. What am I missing or doing wrong?
I have two groups of divs (one with class attacker, and other enemy) with three elements each. I am trying to select one element from each side by making a border around it. Now i want to toggle classes from a attacker to enemy and the other way.
But when I use for loop it somehow ignores some elements and changes only one or two div classes. Here is my code:
HTML:
<div id="army1">
<div class="attacker">
<img src="img/Man/Archer.jpg" />
<div class="hp"></div>
</div>
<br><div class="attacker">
<img src="img/Man/Knight.jpg" />
<div class="hp"></div>
</div>
<br><div class="attacker">
<img src="img/Man/Soldier.jpg" />
<div class="hp"></div>
</div>
<br>
</div>
<div id="army2">
<div class="enemy">
<img src="img/Orcs/Crossbowman.jpg" />
<div class="hp"></div>
</div>
<br><div class="enemy">
<img src="img/Orcs/Mine.jpg" />
<div class="hp"></div>
</div>
<br><div class="enemy">
<img src="img/Orcs/Pikeman.jpg" />
<div class="hp"></div>
</div>
<br>
</div>
And my javascript code:
var attacker = document.getElementsByClassName('attacker');
var enemy = document.getElementsByClassName('enemy');
var button = document.getElementById("fight");
// var class1 = document.getElementsByClassName("first")[0].getAttribute("class");
// class1 = class1.split(" ");
//choose attacker
for (var i = 0; i < attacker.length; i++) {
attacker[i].onclick = function () {
//select only one attacker and set its id to attackerid
if (this.getAttribute('class') != 'attacker first') {
resetAttackerClasses();
this.setAttribute('class', 'attacker first');
} else {
resetAttackerClasses();
}
};
}
//choose enemy
for (var i = 0; i < enemy.length; i++) {
enemy[i].onclick = function () {
//select only one attacker and set its id to enemyid
if (this.getAttribute('class') != 'enemy second') {
resetEnemyClasses();
this.setAttribute('class', 'enemy second');
} else {
resetEnemyClasses();
}
};
}
//fight
button.onclick = function() {
//take off enemy health
document.getElementsByClassName('enemy second')[0].children[1].style.width = '50px';
resetAttackerClasses();
resetEnemyClasses();
for (var i = 0; i < attacker.length; i++) {
attacker[i].setAttribute('class', 'enemy');
enemy[i].setAttribute('class', 'attacker');
};
};
function resetAttackerClasses() {
for (var i = 0; i < attacker.length; i++) {
attacker[i].setAttribute('class', 'attacker');
};
}
function resetEnemyClasses() {
for (var i = 0; i < attacker.length; i++) {
enemy[i].setAttribute('class', 'enemy');
};
}
It's because you're removing the class that was used to fetch the element, which means the element will automatically be removed from the live NodeList (since it no longer matches the query).
When this happens, the NodeList is reindexed, so the next element becomes the current one, and you end up skipping over it with the next i++;
To fix it, iterate in reverse instead.
If you don't want to go in reverse, then decrement the index every time you remove an element from the list.

Javascript Elements with class / variable ID

There's a page with some HTML as follows:
<dd id="fc-gtag-VARIABLENAMEONE" class="fc-content-panel fc-friend">
Then further down the page, the code will repeat with, for example:
<dd id="fc-gtag-VARIABLENAMETWO" class="fc-content-panel fc-friend">
How do I access these elements using an external script?
I can't seem to use document.getElementByID correctly in this instance. Basically, I want to search the whole page using oIE (InternetExplorer.Application Object) created with VBScript and pull through every line (specifically VARIABLENAME(one/two/etc)) that looks like the above two into an array.
I've researched the Javascript and through trial and error haven't gotten anywhere with this specific page, mainly because there's no tag name, and the tag ID always changes at the end. Can someone help? :)
EDIT: I've attempted to use the Javascript provided as an answer to get results, however nothing seems to happen when applied to my page. I think the tag is ALSO in a tag so it's getting complicated - here's a major part of the code from the webpage I will be scanning.
<dd id="fc-gtag-INDIAN701" class="fc-content-panel fc-friend">
<div class="fc-pic">
<img src="http://image.xboxlive.com/global/t.58570942/tile/0/20400" alt="INDIAN701"/>
</div>
<div class="fc-stats">
<div class="fc-gtag">
<a class="fc-gtag-link" href='/en-US/MyXbox/Profile?gamertag=INDIAN701'>INDIAN701</a>
<div class="fc-gscore-icon">3690</div>
</div>
<div class="fc-presence-text">Last seen 9 hours ago playing Halo 3</div>
</div>
<div class="fc-actions">
<div class="fc-icon-actions">
<div class="fc-block">
<span class="fc-buttonlabel">Block User</span>
</div>
</div>
<div class="fc-text-actions">
<div class="fc-action"> </div>
<span class="fc-action">
View Profile
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Compare Games
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Send Message
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Send Friend Request
</span>
</div>
</div>
</dd>
This then REPEATS, with a different username (the above username is INDIAN701).
I tried the following but clicking the button doesn't yield any results:
<script language="vbscript">
Sub window_onLoad
Set oIE = CreateObject("InternetExplorer.Application")
oIE.visible = True
oIE.navigate "http://live.xbox.com/en-US/friendcenter/RecentPlayers?Length=12"
End Sub
</script>
<script type="text/javascript">
var getem = function () {
var nodes = oIE.document.getElementsByTagName('dd'),
a = [];
for (i in nodes) {
(nodes[i].id) && (nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i]));
}
alert(a[0].id);
alert(a[1].id);
}
</script>
<body>
<input type="BUTTON" value="Try" onClick="getem()">
</body>
Basically I'm trying to get a list of usernames from the recent players list (I was hoping I wouldn't have to explain this though :) ).
var getem = function () {
var nodes = document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i].id.split('-')[2]));
}
alert(a[0]);
};
please try it by clicking here!
var getem = function () {
var nodes = document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i]));
}
alert(a[0].id);
alert(a[1].id);
};
try it out on jsbin
<body>
<script type="text/javascript">
window.onload = function () {
var outputSpan = document.getElementById('outputSpan'),
iFrame = frames['subjectIFrame'];
iFrame.document.location.href = 'http://live.xbox.com/en-US/friendcenter/RecentPlayers?Length=1';
(function () {
var nodes = iFrame.document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i].id.split('-')[2]));
}
for (var j in a) if (a.hasOwnProperty(j)) {
outputSpan.innerHTML += (a[j] + '<br />');
}
})();
};
</script>
<span id="outputSpan"></span>
<iframe id="subjectIFrame" frameborder="0" height="100" width="100" />
</body>
What does "I can't seem to use document.getElementsByID correctly in this instance" mean? Are you referring to the fact that you are misspelling getElementByID?
So...something like this (jQuery)?
var els = [];
$('.fc-content-panel.fc-friend').each(function() {
els.push(this));
});
Now you have an array of all the elements that have both of those classes.

Categories