Can't get child div IDs within each parent div/class - javascript

When I try to get child div IDs within each parent div/class I get the error "Uncaught TypeError: Cannot set property '0' of undefined". I am using this javascript with scriptaculous so I have turned off the "$" shortcut.
Example HTML:
<div id="group1" class="section">
<h3 class="handle"><input type="hidden" name="groupName1" value="MyGroup1">MyGroup1</h3>
<div id="item_73548" class="lineitem">item a</div>
<div id="item_73386" class="lineitem">item b</div>
<div id="item_73163" class="lineitem">item c</div>
</div>
<div id="group2" class="section">
<h3 class="handle"><input type="hidden" name="groupName2" value="MyGroup2">MyGroup2</h3>
<div id="item_73548" class="lineitem">item d</div>
<div id="item_73386" class="lineitem">item e</div>
<div id="item_73163" class="lineitem">item f</div>
</div>
The Javascript:
$.noConflict();
var sections = document.getElementsByClassName('section');
var groups = new Array();
for (i = 0; i < sections.length; i++) {
var section = sections[i];
var sectionID = section.id;
var j = 0;
jQuery.each(jQuery("#" + sectionID + " .lineitem"), function () {
groups[i][j] = jQuery(this).attr('id');
j++;
});
}
console.log(groups);
The output should be:
groups[0][0]="item_73548";
groups[0][1]="item_73386";
groups[0][2]="item_73163";
groups[1][0]="item_73548";
groups[1][1]="item_73386";
groups[1][2]="item_73163";
Fiddle here: http://jsfiddle.net/qy9dB/3/

You just need to make sure that groups[i] is setup as an array before you try and add 2nd level elements to the array.
$.noConflict();
var sections = document.getElementsByClassName('section');
var groups = new Array();
for (i = 0; i < sections.length; i++) {
var section = sections[i];
var sectionID = section.id;
groups[i] = [];
var j = 0;
jQuery.each(jQuery("#" + sectionID + " .lineitem"), function () {
groups[i][j] = jQuery(this).attr('id');
j++;
});
}
console.log(groups);

Related

Append many divs inside of a div

In order to animate images in - I need to add many divs using Javascript over the image where at present the markup is
<div class="js-img-in">
<figure><img src="test.jpg"></figure>
</div>
To eventually compile to
<div class="js-img-in">
<div class="js-anim-img-in"></div>
<div class="js-anim-img-in"></div>
<div class="js-anim-img-in"></div>
<div class="js-anim-img-in"></div>
<div class="js-anim-img-in"></div>
<figure><img src="test.jpg"></figure>
</div>
My code at the moment returns appendChild is not a function.
const imageAnimIn = () => {
const images = document.querySelectorAll(".js-img-in");
for (var x = 0; x < 5; x++) {
var imageOverDivs = document.createElement('div');
imageOverDivs.className = "js-anim-img-in";
images.appendChild(imageOverDivs);
}
}
This error took me to this S.O article. createTextNode here, however, will not help me as I am adding an element node, not text.
Will querySelectorAll not work in this instance?
You want querySelector(), not querySelectorAll(). Then you want Node.insertBefore(), and pass in the figure element as the second argument.
const imageAnimIn = () => {
const image = document.querySelector(".js-img-in")
const fig = document.querySelector(".js-img-in > figure")
for (var x = 0; x < 5; x++) {
var imageOverDivs = document.createElement('div');
imageOverDivs.className = "js-anim-img-in";
image.insertBefore(imageOverDivs, fig)
}
}
imageAnimIn()
.js-anim-img-in::after{
content: "New Div"
}
<div class="js-img-in">
<figure><img src="http://placekitten.com/100/100"></figure>
</div>
<!--<div class="js-img-in">
<div class="js-anim-img-in"></div>
<div class="js-anim-img-in"></div>
<div class="js-anim-img-in"></div>
<div class="js-anim-img-in"></div>
<div class="js-anim-img-in"></div>
<figure><img src="test.jpg"></figure>
</div>-->
Did you mean to loop through images.length, and use the image position? Because the result of document.querySelectorAll is a NodeList, not just a single node.
const imageAnimIn = () => {
const images = document.querySelectorAll(".js-img-in");
for (var x = 0; x < images.length; x++) { // Loop through each result
for (var _ = 0; _ < 5; _++) { // Updated to disregard variable
var imageOverDivs = document.createElement('div');
imageOverDivs.className = "js-anim-img-in";
images[x].appendChild(imageOverDivs); // Added [x]
}
}
}

append images from DB into a div in jQuery

I am trying to show images of a particular holiday package from my DB into a slider using jQuery append. My slider is inside a modal and this modal is shown from javascript function. But I am only getting one image into the slide show. I am using while loop to iterate the image array and it is added to the div using innerhtml. I don't know where I am going. Can anyone please help me?
Here is my code:
js
function showDetailsModal(id) {
$.post('uae-holidaydetails.php',{uaeid:""+id+""},function(data){
data = jQuery.parseJSON(data);
var datadet= data[0];
if(data[1]) {
var dataimg= data[1];
var imgarray=[];
for (index = 0; index < dataimg.length; index++) {
imgarray.push(dataimg[index].image);
}
var i=0;
while(imgarray[i]){
document.getElementById("detail-banner").innerHTML='<div class="item"><img src="../sysimages/origimages/'+imgarray[i]+'" alt=""></div>'; //here I am creating the div for slider
i++;
}
}
document.getElementById("uaetitle").innerHTML= datadet.title;
document.getElementById("subtitle").innerHTML= datadet.subtitle;
$('#holiday-details').modal('show'); //modal is shown
});
}
php
<?php
include_once("index.class.php");
$objScr = new INDEX();
if(isset($_POST['uaeid'])) {
$uaeid=$_POST['uaeid'];
$rslthlydata = $objScr->getUaedata($uaeid); //get holiday details
$rowuaedetails = $rslthlydata->fetchAssoc();
$resultimages= $objScr->getUaeholyImages($uaeid); //get images
while($resultimg=$resultimages->fetchAssoc()) {
$dataimg[]=$resultimg;
}
echo json_encode(array($rowuaedetails,$dataimg)) ;
}
html
<div class="modal fade" id="holiday-details" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">CLOSE <img src="images/close-btn.png" alt=""></button>
<div class="modal-body">
<!--<section class="banner detailed"></section> -->
<div class="owl-carousel owl-theme" id="detail-banner" >
//this is the slider
</div>
<div class="details">
<h3 class="top-line" id="uaetitle"></h3>
<h4 id="subtitle"></h4>
</div>
</div>
</div>
</div>
</div>
Edit 1
I tried append also. When I append I am getting the whole images but it's not shown as slider
$('#detail-banner').append('<div class="item"><img src="../sysimages/origimages/'+imgarray[i]+'" alt=""></div>');
Try this, no need to mix pure JS and jQuery. Pick one and stick to it ;)
jQuery(document).ready(function($){
function showDetailsModal(id) {
$.post('uae-holidaydetails.php', {uaeid: id }, function(data) {
var data = JSON.parse(data);
var dataDet = data[0];
if(data[1]) {
var dataImg = data[1];
var imgArray = [];
for (var index = 0; index < dataImg.length; index++) {
imgArray.push(dataImg[index].image);
}
var items = "";
for (var j = 0; j < imgArray.length; i++) {
items += '<div class="item"><img src="../sysimages/origimages/'+imgArray[j]+'" alt=""></div>';
}
$('#detail-banner').append(items);
}
$('#uaetitle').append(dataDet.title);
$('#subtitle').append(dataDet.subtitle);
$('#holiday-details').modal('show'); //modal is shown
});
}
});
You have to concat your image array data using + to create all images.You have to use innerHTML += to avoid replacing the content of a node Like following.
function showDetailsModal(id) {
$.post('uae-holidaydetails.php',{uaeid:""+id+""},function(data){
data = jQuery.parseJSON(data);
var datadet= data[0];
if(data[1]) {
var dataimg= data[1];
var imgarray=[];
for (index = 0; index < dataimg.length; index++) {
imgarray.push(dataimg[index].image);
}
var i=0;
var imageContent = "";
for (var j = 0; j < imgArray.length; i++) {
imageContent +='<div class="item"><img src="../sysimages/origimages/'+imgarray[j]+'" alt=""></div>'; //here I am creating the div for slider
}
}
document.getElementById("detail-banner").innerHTML = imageContent;
document.getElementById("uaetitle").innerHTML= datadet.title;
document.getElementById("subtitle").innerHTML= datadet.subtitle;
$('#holiday-details').modal('show'); //modal is shown
});
}
For example let's consider the following scenario:
var array = [1,2,3,4];
for(var i=1;i<=array.length;i++){
document.getElementById("test1").innerHTML = i+" ";
}
for(var j=1;j<=array.length;j++){
document.getElementById("test2").innerHTML += j+" ";
}
<div id="test1"></div>
<div id="test2"></div>

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>

append method is not working in for loop

I have multiple json object and each object have multiple same, For example:
A->
- A1
-A1A
-A1A
- A2
-A2A
-A2A
- A3
-A3A
-A3A
I have tired to execute in below code but it's not working. Can you please suggest me what is the issue in my code?
subscriptionbarMyData = JSON.parse(window.localStorage.getItem('subscriptionBarJson'));
$('.total-month-cost-product-header-names').text('').addClass('hidden');
for (var key in subscriptionbarMyData) {
if (subscriptionbarMyData.hasOwnProperty(key)) {
var val = subscriptionbarMyData[key];
$('.total-month-cost-product-header')
.find('.total-month-cost-product-header-names')
.removeClass('hidden')
.addClass('show')
.text(val.Name + val.ProductPrice);
var addonvalue = subscriptionbarMyData[key]["Add-on"];
for (var keyval in addonvalue) {
if (addonvalue != undefined) {
var TotalOneCostProduct = $('.total-month-cost-product-items').text('');
for (var keyval in addonvalue) {
// var dataValues = addonvalue[keyval].Name;
$('.total-month-cost-product-header-names')
.text(addonvalue[keyval].Name)
.appendTo(TotalOneCostProduct);
}
}
}
}
}
<div class="summary-block">
<div class="total-month-cost-summary">
<div class="total-month-cost-product-header">
<div class="total-month-cost-product-header-names"></div>
<div class="total-month-cost-product-header-price"></div>
</div>
<div class="total-month-cost-product-items">
<div class="total-month-cost-product-item-names"></div>
<div class="total-month-cost-product-item-price"></div>
</div>
</div>
</div>

jQuery: Return multiple dynamic variables from a FOR LOOP

I want to count all elements with a class of .step then make a for loop and return variables that select each of the corresponding element. Here's my code:
var steps = $('.step').length;
var i = 0;
for (var i = 0; i < steps; i++) {
return var step + i = $('.step' + i);
}
EDIT: To make myself clear, instead of doing it like this:
var step1 = $('.step1.');
var step2 = $('.step2.');
// etc..
I want to use a for loop to get each element with a class of .step and return each one in a different variable, like so: step1, step2, etc. How can I do this?
My best guess for what you want is this:
var result = [];
$('.step').each(function(i) {
result.push( $('.step' + i) );
});
return result;
That will return an array of [all the .step1 elements, all the .step2 elements, ...]
If you want all the data in an array, you can try something like this:
var data = $(".step").map(function(s, index) {
return $(".step" + (s + 1));
});
console.log(data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="step step1">1</div>
<div class="step step2">2</div>
<div class="step step3">3</div>
<div class="step step4">4</div>
<div class="step step5">5</div>
<div class="step step6">6</div>
But I would rather suggest you to store data in an object. This would be easier to access.
var obj = {};
$(".step").each(function(i, el) {
var _i = i + 1;
obj["step" + _i] = $(".step" + _i);
});
console.log(obj)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="step step1">1</div>
<div class="step step2">2</div>
<div class="step step3">3</div>
<div class="step step4">4</div>
<div class="step step5">5</div>
<div class="step step6">6</div>

Categories

Resources