+ 2
How to select img element from second div element using javascript
Here's the code: <!DOCTYPE html> <html> <head> <title>How to select img element from from second div element</title> </head> <body> <div id="test1"> <img id="img1" class="ex1"/> </div> <div id="test2"> <img id="img1" class="ex1"/> </div> </body> </html> https://code.sololearn.com/Wv4Gq6SB5uHi/?ref=app
20 Antworten
+ 1
document.querySelector("#test2 #img1").id = "yourId";
+ 5
Try this
var image = document.querySelector("#test2 #img1");
+ 4
Dear Jayakrishna
You are breaking rules of html wildly. How do you expect to run the code properly?
You gave two different image elements same id. Seriously 🤔
No Offence!
+ 4
Didn't even notice that. id property should be unique
+ 4
Assign two IDs and access them using javascript.....(getElementById)
+ 2
Ipang thanks for your instant reply. Now I have a problem with another one. How can I change the id of img1 to img5. Here's is the code:
https://code.sololearn.com/Wl9fxdc9tW9V/?ref=app
+ 2
Artur but we have two img1 id's in two different divs.
I'm beginner in html sorry of I'm asking too many questions
+ 2
Arthur thank you so much. Now I uderstood. Again thanks for sharing your knowledge♥
+ 2
There are two ways:
1:
document.querySelector("#test2 #img1");
2:
document.getElementById("img1");
document.getElementById("test2");
+ 1
Try this
var image = document.querySelector("#test2 #img1");
+ 1
Wrong code you gave the images the same class of id. The code will run abnormally
+ 1
Actually, technically you can use same id for different elements, and It works fine(just as classes). But you should never do that, because in large projects you might get lost, trying to differentiate which id is unique and applied to one specific element (what it's suppose to do), and which is applied to N elements as a class.
+ 1
You can change before or after it loaded. You have done it right in your second code. If you want on load then your code should be like; window.onload = function() {
//your code
}();
+ 1
\•/ Thank you
0
let secondImg = document.getElementById(img1);
0
oh yeah that's the problem
0
Happy coding brother. Keep it up, you can do it!
0
You cant use two same id element, img1 and img1. Change one of them then use document.querySelector('id')
0
Not to be perfect
- 1
document.getElementById("img1").id = "yourNewId";