I am a beginner in Javascript and am working on a few smaller projects in tampermonkey to build my knowledge.
In one of my projects, I am trying to use javascript to change the text color of h1. This sounds like a really simple thing but for whatever reason, nothing I've tried so far has worked as expected.
I've tried using Stylebot to inject the CSS equivalent which works perfectly fine.
Here are the Javascript methods that I have tried (using #ffff00 as an example):
For the two examples below, I have also tried replacing getElementsByTagName
with getElementById
, querySelector/querySelectorAll
, and getElementsByClassName
let hexValue = "#ffff00"
document.getElementsByTagName("h1").style.color = hexValue;
let h1 = document.getElementsByTagName("h1")
h1.style.color = "#ffff00"
Original code I was trying at the beginning which takes hex code from a user input:
let tc1 = document.getElementsByTagName("h1");
let btn = document.createElement("button")
btn.textContent = 'update'
btn.addEventListener('click', changeTextColor)
let jsc = document.createElement("input");
jsc.setAttribute('id', 'hexInput');
jsc.setAttribute("data-jscolor", "{}")
function changeTextColor() {
jsc.addEventListener('change', function() {
let hexValue = this.value; //in this line, i have also tried document.getElementById('hexInput').value
tc1.style.color = hexValue;
}
document.body.insertAdjacentElement('beforebegin', jsc)
document.body.insertAdjacentElement('beforebegin', btn)
jscolor.install()