Skip to content
Advertisement

How to change the styling of an element using JS when it has no class or ID?

I have a html file (converted from docx) and it does not have any class names or ids. How can I style it using JS? For example, if I need to change the color of the heading for the below file HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="./script.js"></script>
    <title>Document</title>
  </head>
  <body>
    <h1>This is the heading</h1>
    <p>Hello, my name is xyz and this is a para</p>
  </body>
</html>

This is what I tried, but document.getElementByTagName() does not return the element like document.getElementById()

console.log('hello world');
Heading = document.getElementsByTagName('h1');
console.log(Heading);
Heading.style.color = 'blue';

Edit: I tried the below code, but it returns undefined

console.log('hello world');
Heading = document.getElementsByTagName('h1')[0];
console.log(Heading);
Heading.style.color = 'blue';

enter image description here

Advertisement

Answer

Please update your code like this. you imported the script before html. There are two solutions. first you have to import script after html or use

window.addEventListener

window.addEventListener('load', () => {
  const heading = document.querySelector('h1');
  heading.style.color = 'blue';
});
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement