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
Related
I'm building a shop section for a school project. It works like a gallery: when clicking on an card, a new display opens up with fullscreen info about the product: img, product title, price... I've managed to match the image of the fullscreen display to the one clicked (you won't see the images since it's a relative URL).
Now I need to match the rest of the info.
const miniaturas = document.querySelectorAll(".galeria a");
const modal = document.querySelector(".modal");
const imgModal = document.querySelector(".modal img");
const plantNames = document.querySelectorAll(".galeria h3")
const plantNameModal = document.querySelector(".modal h3");
miniaturas.forEach(function(miniatura){
miniatura.addEventListener("click", function(evento){
evento.preventDefault();
imgModal.setAttribute("src",miniatura.getAttribute("href"));
modal.classList.add("visible");
for(i = 0; i < miniaturas.length; i++){
plantNameModal.innerHTML = plantNames[i].innerHTML;
}
})
})
modal.addEventListener("click", function(){
modal.classList.remove("visible");
})
I don't know how to get the innerHTML via each item's index. I've tried using a for loop and the parameter "miniatura" from the function. CodePen here.
You can get the index of each miniatura as the second argument to the handler function you pass to the forEach. You have access to this index within the body of the addEventListener, as in:
miniaturas.forEach(function(miniatura, index){
miniatura.addEventListener("click", function(evento){
evento.preventDefault();
imgModal.setAttribute("src",miniatura.getAttribute("href"));
modal.classList.add("visible");
// instead of for loop, use `index` to access
// the corresponding elements in the arrays:
plantNameModal.innerHTML = plantNames[index].innerHTML;
})
});
I have forked your Pen.
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>
Would there be any reason the following code would not insert a DIV into the DOM and add the ID attribute? For some reason it is not working:
createDivs() {
const target = document.querySelector(".navbar");
const createDiv = document.createElement("DIV");
createDiv.setAttribute("id", "result-div");
createDiv.innerHTML = "<p>Yes</p>";
createDiv.insertAdjacentElement("afterbegin", target);
}
ngOnInit() {
this.createDivs();
}
You called insertAdjacentElement on the new element instead of on the sibling element... check the documentation
Instead of using
createDiv.insertAdjacentElement("afterbegin", target);
you should use
target.insertAdjacentElement("afterbegin", createDiv);
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
So I have the following HTML...
HTML:
<div id="col1">
<img src="1.jpg">
</div>
And I am implementing a HTML5 drag and drop feature where the inner html of col1 is changed for the dragged element's inner html - so basically the columns change their content.
I have another div (let's call that swap-text) where I want to change its text content depending on what image is presently inside col1.
This is why I want to figure out how I can obtain col1's img element's src attribute value through JavaScript so I can then write an if statement to change the content of the swap-text depending on which image is in col1.
I could add ID's to the img elements but then I still don't know how I would write the condition to check if say, img-id1 parent is col1.
Attempt(s):
var doc = document.getElementById("col1");
var children = null;
var imgEle;
//gets img node, but also got 1/2 text object(s)?
for (var i = 0; i < doc.childNodes.length; i++) {
children = doc.childNodes[i];
console.log(children);
}
//document.getElementById("img")
//children[1].getAttribute('src'); - cannot call method 'getAttribute' of undefined
//imgEle = doc.childNodes[0].getElementById('img'); - Object #<Text> has no method 'getElementById'
console.log(imgEle);
console.log(children);
This work fine pure javascript:
document.getElementById("col1").getElementsByTagName("img")[0].getAttribute("src");
var doc = document.getElementById("col1");
var img = document.getElementsByTagName('img')[0];
var imgParent = img.parentElement;
This is how you determine the elements parent/
I suggest you to use JQuery so you can simply use:
$("img").attr("id"); //Return the id of the img element
Check this:
var column = document.getElementById("col1");
var imgSrc = column.getElementsByTagName("img")[0].getAttribute("src");
Or just use the jQuery - it's simpler:
$('#col1 img').attr('src');
as you will only have one child node in col1 (the img), change the for loop.
var doc = document.getElementById("col1");
var children = null;
var imgEle;
//gets img node, but also got 1/2 text object(s)?
//for (var i = 0; i < doc.childNodes.length; i++) {
// children = doc.childNodes[i];
// console.log(children);
//}
childen = doc.childNodes[0];
// or children = doc.firstChild;
console.log(children);
//document.getElementById("img")
console.log(children.getAttribute('src')); - children is single object
//imgEle = doc.childNodes[0].getElementById('img'); - Object #<Text> has no method 'getElementById'
console.log(imgEle);
console.log(children);