Jquery "for" loop to find how many children - javascript

I am trying to alert how many children are in a div with the class ".child". Ex: There are five ".child" inside of a div. I am not sure why my for loop to do this doesn't work, and I realize there are better ways but I am practicing for loops. Thanks. The problem can be found here http://jqexercise.droppages.com/#page_0013_
for (var i = 1; i < 100; i++){
if($(".child:nth-child(i)") == true){
}
else {
alert(i);
break;
}
}

You can get number of .child in a div like following.
var num = $('div').find('.child').length;
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
<span class="child">Child</span>
</div>
Update: If you want to use for loop then you can do it like below using jquery eq() function.
for (var i = 0; i < 100; i++) {
if ($('.child').eq(i).length) {
}
else {
alert(i);
break;
}
}
You used i as string. Using nth-child() do it like below.
for (var i = 1; i < 100; i++) {
if ($(".child:nth-child(" + i + ")").length) {
}
else {
alert(i-1);
break;
}
}

Another way:
alert($('div .child').length);

i inside if condition is a string, not a variable, do this :
if ( $( ".child:nth-child(" + i + ")" ) == true )

var intChildrenCount = $("div .child").length;

var arrChildren = $("div .child");
$.each(arrChildren,function(){
// Here you will get child's HTML one by one
console.log($(this).html());
});

Related

Javascript DOM | Find element by inner Text and replace every element that matches

Here's the code I scraped from the internet and done something to it, I don't know anything about Javascript so don't blame me if this code is a total mess :)
My Code:
var aTags = document.getElementsByTagName("a");
var searchText = "VRX";
var found;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].textContent == searchText) {
found = aTags[i];
break;
}
}
Array.from(found).forEach(
function(element, index, array) {
document.getElementsByClassName("nova").style = "text-shadow:0.5px 0.5px 5px gold;color:gold;background: url(https://static.nulled.to/public/assets/sparkling.gif);-webkit-animation: randclanim 2s infinite linear;";
}
);
HTML:
As I see screenShot of your code, you should parsing span elements for example I write below code:
// if you want just A elements use below line
var els = document.getElementsByTagName("span");
for (i = 0; i < els.length; i++) {
console.log(els[i].textContent +"--" + i );
els[i].className.lastIndexOf('nova')!=-1 && els[i].textContent.lastIndexOf('VRX')!=-1 ? els[i].style = "text-shadow:0.5px 0.5px 5px gold;color:gold;background: url(https://static.nulled.to/public/assets/sparkling.gif);-webkit-animation: randclanim 2s infinite linear;" : 0;
}
<body>
<div>
<span class="nova">HI</span>
<br>
<br>
<a > VRX </a>
</div>
<div>
<a> <span class="nova">VRX</span></a>
</div>
</body>
I hope it useful ;)

Loop through div children and bold specific text not working

I have a suggestion dropdown under an input field and I am trying to make the text in the suggestion divs bold for the portion that matches what is currently in the input field.
e.g
input: AB
dropdown: ABCDE
My current code doesn't seem to be replacing the div content with the span
JS:
BoldMatchedText(inputToMatch:string){
var outerDiv = document.getElementById("dropdown");
if(outerDiv != null){
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++){
subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
html:
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">{{reg1}}</div>
<div class="reg-list-item">{{reg2}}</div>
<div class="reg-list-item">{{reg3}}</div>
<div class="reg-list-item">{{reg4}}</div>
</div>
</form>
You need to assign the result of calling the function replace.
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
function BoldMatchedText(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
BoldMatchedText('Go');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>
Try this working sample with a benchmark. Compared with the previous answer.
function BoldMatchedText1(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
function BoldMatchedText2(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if(outerDiv !== null) {
// Use `getElementsByClassName` instead using `getElementsByTagName('div')` JS will traverse your entire HTML file and look for all div tags, may take a little longer if you have a lot
var items = outerDiv.getElementsByClassName("reg-list-item");
// Getting the iteration length before the loop will give you performance benefit since items.length will not be checked per iteration
var len = items.length;
// Using while loop evaluating only if len is any positive number (true) except 0 (false) with reverse iteration making it faster
while(len--) {
var item = items[len].innerHTML;
// ONLY replace the text that contains the `inputToMatch`
if(item.indexOf(inputToMatch) !== -1) {
items[len].innerHTML = item.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
}
console.time('filter1');
BoldMatchedText1('Gom');
console.timeEnd('filter1');
console.time('filter2');
BoldMatchedText2('Gom');
console.timeEnd('filter2');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>

Changing the name of a html class with for loop variable

I have several of html class's incrementing up in class name such as:
<div class="chicken1">
<b></b>
</div>
<div class="chicken2">
<b></b>
</div>
<div class="chicken3">
<b></b>
</div>
I'm trying to write a for loop which will loop through these class names, adding the index to the end each class name and then calling a function in 2s delays.
for ( var i = 1; i <= 3; i++ ) {
setTimeout(function() {
myFunction(".chicken" + i + " b");
}, 2000 * i);
}
However this isn't working.
Fiddle
The problem is actually that of setTimeout() called within a loop; to do this properly you have to close over the loop variable:
for (var i = 1; i <= 6; ++i) {
setTimeout((function(i) {
return function() {
myFunction(".chicken" + i + " i");
};
})(i), i * 2000);
}
Demo
It uses a function that gets called immediately, passing the value of i; this value is retained until the setTimeout() is fired.
are you using jquery? try
for ( var i = 1; i <= 3; i++ ) {
myFunction($(".chicken" + i + " b"));
}
in jquery, to select elements,class etc. we need $("<selector here>");
This works fine for me:
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<div class="chicken1">
<b></b>
</div>
<div class="chicken2">
<b></b>
</div>
<div class="chicken3">
<b></b>
</div>
<script>
$( document ).ready(function() {
for ( var i = 1; i <= 3; i++ ) {
$(".chicken"+i+" b").html("Hey " + i);
}
});
</script>
</body>
</html>

Input number's value to append div's

Fiddle - http://liveweave.com/enRy3c
Here's what I'm trying to do.
Say my input number is 5. I want to dynamically append 5 divs to the class .enfants. However I haven't figured out how to do that. I been searching and searching and I haven't came across anything.
jQuery/JavaScript:
var counter = 1;
// Value number = .enfants children
$(".ajouter-enfants").on('keyup change', function() {
var yourChildren = "<div>" + counter++ + "</div>";
var CallAppend = function() {
$(".enfants").append( yourChildren );
};
// If 0 or empty clear container
if ( $.inArray($(this).val(), ["0", "", " "]) > -1 ) {
$(".enfants").html("");
// If only add/have 1 div in container
} else if ($(this).val() === "1") {
$(".enfants").html("").append( yourChildren );
// If > 0 add as many divs as value says
} else {
$(".enfants").html("");
CallAppend();
}
});
HTML:
<div class="contenu" align="center">
<div>
Value number = .enfants children
</div>
<input type="number" min="0" class="ajouter-enfants" value="0" />
<div class="enfants">
</div>
</div>
How about a simple loop? If you just want to append, try something like this:
$(".ajouter-enfants").on('change', function() {
var numDivs = $(this).val();
var i;
for (i = 1; i <= numDivs; i += 1) {
$('.enfants').append('<div>' + i + '</div>');
}
});
EDIT:
If you want to replace instead of append the newly-created <div>'s, try something like:
$(".ajouter-enfants").on('keyup change', function() {
var content = '';
var numDivs = $(this).val();
var i;
for (i = 1; i <= numDivs; i += 1) {
content += '<div>' + i + '</div>';
}
$('.enfants').html(content);
});
This will replace the entire content of any elements using the class ajouter-enfants with the number of <div>'s specified in the input box.
Try this:
$(".ajouter-enfants").on('keyup change', function() {
var num = +$.trim($(this).val()), target = $(".enfants"), i = 0, s = '';
target.empty();
if (!isNaN(num) && num > 0) {
for (; i < num; i++) {
s += '<div>' + (i + 1) + '</div>';
}
target.html(s);
}
});
How would you get it to only append the value amount? It appends more when the value is (2 becomes 3, 3 becomes 6, 4 becomes 10 and repeats even when I'm decreasing the numeric value) –
#Michael Schwartz
Here is another code example that might be helpfull.
$(".ajouter-enfants").on('change', function() {
var numDivs = $(this).val();
var i;
var html ='';
for (i = 1; i <= numDivs; i += 1) {
html += '<div>' + i + '</div>';
}
$('.enfants').empty().append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contenu" align="center">
<div>
Value number = .enfants children
</div>
<input type="number" min="0" class="ajouter-enfants" value="0" />
<div class="enfants">
</div>
</div>

Background change not working in javascript. whats wrong?

I am using jquery slider, i have a single layout and a center div for content..i need to change the color of the layout while i slide on a different page. This is What i am doing using asp.net mvc3.
HTML:
<div id="iPhone_Product">
<div class="slides_containeriphone" >
#if (Model == null)
{
<div class="animateriphone" id="1" title="iphone">
#Html.Partial("`enter code here`_iPhone_Main")
</div>
<div class="animateriphone" id="2" title="salah">
#Html.Partial("Salah")
</div>
<div class="animateriphone" id="3" title="tasbeeh">
#Html.Partial("_Tasbeeh")
</div>
}
else
{
foreach (string s in Model)
{
<div class="animateriphone">
#Html.Partial(s);
</div>
}
}
</div>
</div>
Javascript:
function color_change() {
var ids = new Array();
ids[0] = '1';
ids[1] = '2';
ids[2] = '3';
for (var item = 0; item < ids.length; item++) {
var x = document.getElementById(ids[item]);
}
if (x.id == '1' && x.title=='iphone') {
$(".st_tabs_container").css({ "background-color": "#c8c7c7" });
}
else
if (x.id == '2' && x.title == 'salah') {
$(".st_tabs_container").css({ "background-color": "yellow" });
}
else
if (x.id == '3' && x.title == 'tasbeeh') {
$(".st_tabs_container").css({ "background-color": "#c8c7c7" });
}
}
$(document).ready(function () {
color_change();
});
i have used this javascript to change the background but its not working, any help would be appericiated.
I think the issue is that you are using numbers for ids. Try starting your id values with letters. I think you should consider prefixing your ids, i.e. id1, id2, or something like that.
And you are closing the for loop too early, Nest all your if/else logic inside it as well.
Isn't x always going to be 3 since you are reseting x inside a loop.
You are looping over all your elements without doing anything to them, so depending on what you are trying to do, you might need to move the if-statements into the for-loop as well, or make use of the x in a proper way from within the for-loop.
Not entirely sure what you want to accomplish, but I've put together what I believe you are trying to do: http://jsfiddle.net/ZuzTU/1/
function color_change() {
var ids = new Array(); ids[0] = '1'; ids[1] = '2'; ids[2] = '3';
for (var item = 0; item < ids.length; item++) {
var x = document.getElementById(ids[item]);
if (x.id == '1' && x.title=='iphone') {
$("#" + x.id).css({ "background-color": "#c8c7c7" });
}
else if (x.id == '2' && x.title == 'salah') {
$("#" + x.id).css({ "background-color": "yellow" });
}
else if (x.id == '3' && x.title == 'tasbeeh') {
$("#" + x.id).css({ "background-color": "#c8c7c7" });
}
}
}
$(document).ready(function () {
color_change();
});​
Pretty sure you're not calling the ids right, try this:
<div class="animateriphone" id="id2" title="salah">
var x = document.getElementById('id'+ ids[item]);

Categories

Resources