Hi,
I would like to get access to all img classes:
<div class="row">
<img src="pictures/back-card.jpg" class="card">
<img src="pictures/back-card.jpg" class="card">
<img src="pictures/back-card.jpg" class="card">
<img src="pictures/back-card.jpg" class="card">
</div>
I got HTMLCollections by using getElementByClassName, how I can get all classes named ‘card’?
Thank you
You can use querySelector instead, which has become quite the versitile technique that lets you get elements using CSS selectors.
var card = document.querySelector(".card");
Edit:
The above is for just one element. Use querySelectorAll as in my next post, for multiple cards.
1 Like
This doesn’t work. I was trying this before. The problem is that I got only one img tag like here:
I want to get access to all imgs tags and classes inside.
querySelectorAll() is used to get more than one of them.
var cards = document.querySelectorAll(".card");
I was also trying to go this way.
and the result is the same:
Additionally, I wrote var card = document.querySelectorAll('img.card');
and I got the same result.
What I was tryning is:
getElementsByTagName,
getElementsByClassName,
getElementById, not, because there is a few classes
querySelectorAll,
querySelector
nothing is working.
Here is me code:
https://jsbin.com/hoyuriyuza/edit?html,css,js,console,output
Thank you, for any help
Logging the length of it shows that it has 16 items. I recommend that you call the variable cards
instead of card
though, to help remove any confusion.
1 Like
Ok , you’re right. Do you have any idea, how I can ‘catch’ the all classes .cards
?
Thank you for your time.
What do you mean by catch
, and is the .cards class different from the .card class?
let cards represent more than 1 card, so I changed the name for plural name - ‘cards’.
I would like to get access to all single img tags or cards classes and then us it in js file, but what I got is NodeList or HTMLCollections
deringmagdalena:
let cards represent more than 1 card, so I changed the name for plural name - ‘cards’.
I would like to get access to all single img tags or cards classes and then us it in js file, but what I got is NodeList or HTMLCollections
You can iterate through each of those cards in the nodeList or HTMLCollection using the forEach method:
cards.forEach(function (card) {
// do stuff with each card
});
1 Like
Thank you, this is working.
system
Closed
April 3, 2018, 1:24pm
12
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.