Hi i want to getfocus to image link by javascript, the problme is that i don't have directly access to my image.
<li classe="product-1">
<div classe="shop">
<a src="xxxxxx">
<img >
</a>
</div>
</li>
i tried using access to give focus to the image but doesn't work
var imaglink = document.getElementsByClassName("product-1")[0].getElementsByClassName("shop")[0].getElementsByClassName("img-link")[0];
imagelink.focus();
if anyone have any suggestion ho to resolve this probleme i will be thankful
CodePudding user response:
Possible typo, depending on language I think... I notice in your code you have some lines with classe="..." other times
with your li element have classe, that might be returning an undefined value, so the rest of your selection isn't going to work.
CodePudding user response:
const img = document.querySelector("li a > img")
img.focus()
or
const img = document.querySelector(".shop > a img")
or if there multiple images
const img = document.querySelectorAll(".product-1 img")[0]
CodePudding user response:
You can just combine the selectors together and use querySelector
like
document.querySelector(".product-1 .shop .img-link").focus();
document.querySelector(".product-1 .shop .img-link").focus();
a:focus{
display:inline-block;
border:20px solid #ccc;
}
<li >
<div >
<a href >
<img src="https://picsum.photos/200/300">
</a>
</div>
</li>