looping over nested array to create elements with js/jquery - javascript

I come with a problem, I hope you can help me solve.
I have already searched on this side quite a bit, but couldn't find an answer that solves my problem. I recently worked with looping over objects with jquery each and that worked fine. ATM I need to loop over entries of an array.
This is an example of how the array looks. It contains arrays, which themselves contain the src of an img and the title of the img.
var imgRef = [[http://127.0.0.1:5555/images/imgf0002.png, fig number 1],[http://127.0.0.1:5555/images/imgf0012.png, fig number 12]]
What I would like to do is to loop over the arrays and create a div for each entry. Inside the divs there should be an img containing the src of the other array and a p tag with the name. Then this will be appended to another element on the website.
<div>
<img src="http://127.0.0.1:5555/images/imgf0002.png">
<p>Fig number 1</p>
</div>
<div>
<img src="http://127.0.0.1:5555/images/imgf0012.png">
<p>Fig number 2</p>
</div>
I have started with this. Just to see whether I can loop over the entries, but it didn't work.
$.each(imgRef, function (index, value) {
$('<div />', {
'text': value
}).appendTo('#localImg');
});

var imgRef = [['http://127.0.0.1:5555/images/imgf0002.png', 'fig number 1'],['http://127.0.0.1:5555/images/imgf0012.png', 'fig number 12']]
$.each(imgRef, function(index, value){
$('.localImg').append('<div><img src="'+value[0]+'"><p>'+value[1]+'</p></div>');
});

you've got to iterate over the array with arr.forEach((elem) => {}) or other iterator methods. Since each of elements of the main array, is an array of two elements, you can use array destructuring and use [url, title] instead of elem in the iterator function. Then in the body create the html string from title and url and append it into your target using $.append method.
let theArray = [["url1","title1"],["url2","title2"] /*,...*/];
theArray.forEach(([url, title]) => {
$('#localImg').append(`<div>
<img src="${url}">
<p>${title}</p>
</div>`);
});

var imgRef = [['http://127.0.0.1:5555/images/imgf0002.png', 'fig number 1'],['http://127.0.0.1:5555/images/imgf0012.png', 'fig number 12']]
$.each(imgRef, function (index, [src, text]) {
// create the div element
const div = $("<div></div>")
// create the image and add src for it.
const img = $('<img />', {
src,
});
// create the p element and add the text to it.
const p = $('<p></p>', {
text
})
// append both image and p in the div
div.append([img, p])
// then insert the block inside the localImage container.
$('#localImg').append(div)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="localImg"></div>

Related

How do you change multiple tags with specific conditions?

I'm trying to create a way to replace tags and content within a string based on a specific condition.
I am able to fully replace the string as intended but this would affect everything with the same initial tag. I can also replace the text within the URL if it contained a string.
The issue is when I'm trying to replace the following:
<figure class="media"><img src="removethis?=banners/image.jpg"></figure>
<figure class="media"><img src="removethis?=thumbnails/image.jpg"></figure>
If I do the following:
var test = $("figure.media").html();
if (test.includes("removethis?=")) {
var img = $("img").attr("src");
var replaceIMG = img.replace("removethis?=", "images/");
$("figure.media").replaceWith('<div class="img"><img src="' + replaceIMG + '"></div>');
}
Then I am able to remove "removethis?=" without any issues, however, it will affect both items. If I code it like this:
var test = $("figure.media").html().includes("banners");
if (test === true) {
var test2 = $("figure.media").html();
if (test2.includes("removethis?=")) {
var img = $("img").attr("src");
var replaceIMG = img.replace("removethis?=", "images/");
$("figure.media").replaceWith('<div class="img"><img src="' + replaceIMG + '"></div>');
}
}
Then I am able to check whether the condition has "banners" or "thumbnails", but adding the previous code again results in both items being changed. Is there a way to accomplish just changing one of the items rather than both? This would also need to work if there are multiple of the same condition.
You need to iterate over each element and within that loop address only the current instance.
You can use the removethis in the selector to filter only the relevant ones and then use attr(attributeName,function) to do all the looping and then finally use wrap() to insert the new div
Something like:
$("figure.media img[src*='removethis?=']").attr('src', function(_, curr) {
return curr.replace("removethis?=", "images/");
}).wrap('<div class="img">');

getting dataset value from a nodeList javascript

I have a nodeList of div and each div has an img with src, id and a dataset.
When looping the nodeList with a forEach loop I store the first element of that div (hence the img) so i can then access to its id, src and dataset. I'm succeeding in getting the id and the src but not the dataset; it always returns an empty DOMStringMap {} .
How can i get this info?
each div has an img like ->
function getCards(){
let totalCards = document.querySelectorAll(".card")
totalCards.forEach(el => {
el.addEventListener("click", function(){
let thisCard = el.children[0]
let thisCardID = thisCard.id
let thisCardDataSet = thisCard.dataset
let thisCardSRC = thisCard.src
console.log(thisCard)
console.log(thisCardID)
console.log(thisCardDataSet)
console.log(thisCardSRC)
})
})
//console.log(flippedCard)
}
´´´
If the dataset is an attribute of your img tag like so:
<img src=".." alt=".." dataset="..." />
Then you will need to grab the attributes object first
let thisCardDataSet = thisCard.attributes.dataset

get the all the id's from a class when the image is selected

I have few uploaded images in one div and I want to move them to another div and update the database table. For that I need the id's of the images selected and the name of the div where I want to move.
I have the id of the selected image using the check box but I am not sure how can I get all id's in the end .
function MoveImages(){
for ( var i = 0; i < $(".ct input[type=checkbox]:checked").length; i++) {
var element = $(".ct input[type=checkbox]:checked")[i];
var parent = element.parentNode;
var id = parent.getAttribute('id');
}
}
how can I get all the id's in the end ?
This is how my class looks like.
<div class="ct" id="559429bc0d559162552c9728">
<input type="checkbox" class="remove">
<img src="/image?id=c9728" data-src="random.JPG" id="previewImagec9728">
</div>
the move function should return all the id's.
With a bit of JQuery's $.each, substring, and JS array methods, you can grab the raw IDs and put them in an array like so:
var ids = [];
//For each element that matches ".ct input[type=checkbox]:checked".
$.each($('.ct input[type=checkbox]:checked'), function() {
//Find the image element, get the id value, and strip the first 12 characters.
var id = $(this).find('img').attr('id').substring(12);
//Put ID in array.
ids.push(id);
});
Use $.map():
var yourIds = $(".ct input[type=checkbox]:checked").map(function(){
return $(this).parent().attr('id');
});
Try jquery's each:
$('.ct').each(function() {
var id = $(this);
})
use :has and .map
$('.ct:has(:checked)').toArray().map(function(element, index) { return element.id })
or
$('.ct:has(:checked)').map(function(index, element) { return element.id }).toArray()
in both cases .toArray() is to get a normal array instead of a jquery array

Finding text length within a divs children

So i have an array of divs. each div contains three span elements. Each span element can contain any number of digits.
This is what i have so far:
var arrayOfDivs = $(".avgMaxClass");
$.each(arrayOfDivs, function (index, value) {
});
what i want to do is calculate the total length of all the text within all the spans within the div im iterating through. I can't figure it how to do that.
EDIT:
To be clear i don't want the total text length of all the divs. I want the text length of the current div that im iterating through
$(".avgMaxClass span").text().length;
JSFiddle demo
Edit:
As you stated in your comment that you want to know the length for each DIV, here is another way using jQuery.each():
var avgMaxClass = $('.avgMaxClass');
$.each(avgMaxClass, function(i,item) {
// Output span text length for each item
console.log($("span", item).text().length);
});
JSFiddle demo
Just iterate over the div and find its length.
$(".avgMaxClass").each(function(){
var thisDivsLength = $(this).find('span').text().length;
alert("Current div's length: " + thisDivsLength);
});
$.each is for non-jQuery objects. Use $.fn.each instead.
DEMO
You can use a selector to get the divs and spans at the same time, or to split the logic and show both parts individually, you can use two selectors and loop over the results of each.
var total = 0;
$(".avgMaxClass").each(function(index, value) {
$(value).find("span").each(function(cindex, child) {
total += $(child).text().length;
});
});
$("#result").text("Total length: " + total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avgMaxClass">
<span>1</span>
<span>12</span>
<span>123</span>
</div>
<div class="avgMaxClass">
<span>1234</span>
<pre>12345</pre>
<span>12345</span>
</div>
<div class="avgMaxClass">
<span>123456</span>
<span>1234567</span>
<span>12345678</span>
</div>
<div id="result"></div>

Select Div Title Text and Make Array With Jquery

I'm trying to add the text from all divs Title Attributes to an array but I can't seem to select the right thing.
I need the title because it will contain the string that I need to use.
Here are three divs with different titles
<div class = 'test' title='title1'>Hello</div>
<div class = 'test' title='title2'>goodbye</div>
<div class = 'test' title='title2'>goodbye</div>
Here is my Jquery so far.
$(document).ready(function() {
$array = $('[title][title!=]').each(function(){
$(this).attr("title").makeArray;})
alert($array)
});
The alert just says [Object object]
In my example I'm trying to select create an array that contains [Title1, Title2, Title3].
Can anyone help me do this?
********************************UPDATE************************************
Thanks the first one worked perfectly. I really appreciate it.
var array = $.map($('[title][title!=""]'), function(el) { return el.title });
FIDDLE
Selects all elements that has a title attribute that is not empty, and maps the titles to an array
var theArray = []; // set an empty array to a variable outside of scope
$('.test').each(function() { // loop through all the .test divs
var theTitle = $(this).attr('title'); // selects the text of the title for the current .test element
theArray.push(theTitle); // this adds the text of the current title to the array
});
console.log(theArray); // just to test and make sure it worked, remove once verify
I'd suggest:
var titles = $('.test').map(function(){
return this.title;
}).get();
References:
get().
map().

Categories

Resources