I have started learning Javascript basics ,here in js i am trying to change the color of element but i am unable to do that even after changing with style.color the color is not changing. Here is my html code of the element i am trying to change the color:
<div class="btn"><a href="#">Login</a></div>
It is a normal button This is my JS code:
let k=document.getElementsByClassName("btn");
k[0].style.color="blue";
If anyone knows what's wrong here please help out.
I tried to change the color using style.color of js document property, and i was expecting th element to change the color
It works, only thing is that your <div> contains a <a> which already had defined style
let k=document.getElementsByClassName("btn");
k[0].style.color="green"; // Links are already in blue, I put green only to see it quickly
<a class="btn" href="#">Login</a>
This does not works because your button itself does not have any text. It's the a tag that has.
There are multiple ways of solving your problem :
If possible, you can just put text in your btn (instead of an a tag, and then change the color of the button as you did.
for example : <button class="btn">Hello world</button>
You can put a class on your a tag and update the tag color which here will work.
For example :
<button class="btn2">
<a href='#' class="link">Hello world</a>
</button>
and then in JS :
const link = document.getElementsByClassName("link")[0]
link.style.color="blue"
You can retrieve the a tag with the button class using querySelector (documentation here)
Example : document.querySelector(".btn3 a").style.color="blue"
// solution 1
const btn1 = document.getElementsByClassName("btn")[0]
btn1.style.color = "red";
// solution 2
const link = document.getElementsByClassName("link")[0]
link.style.color="green"
// solution 3
const link2 = document.querySelector(".btn3 a")
link2.style.color="purple"
<button class="btn">
Hello world
</button>
<button class="btn2">
<a href='#' class="link">Login</a>
</button>
<button class="btn3">
<a href='#'>Login</a>
</button>
Does it have to select by Classname? Just give it an ID and do it like that!
<div class="btn" id="bnt1"><a href="#">Login</a></div>
let k=document.getElementsById("btn1");
k[0].style.color="blue";