JavaScript styling can be unpredictable at times

It seems like there's a mysterious logic at play that I can't quite grasp, and I haven't been able to find a solution online. The application of styles is inconsistent - sometimes they work, sometimes they don't, even though no changes have been made. It's puzzling how commenting out a style for one ID affects another independent ID, and the order in which elements are arranged in the JavaScript document can impact each other's functionality. As someone who is only a few days into learning Javascript, this experience is truly bizarre to me. I am using Live Server on VS Code.

const result = document.querySelector("#myElement");
result.style.color = "blue";
result.style.backgroundColor = "black";
result.style.fontSize = "80px";
let button = document.getElementById("button");
button.style.color = "red";
let para = document.getElementById("p");
para.style.backgroundColor = "black";
para.style.color = "green";

This is the 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" />
    <link rel="stylesheet" href="index.css" type="text/css" />

    <title>Document</title>
  </head>
  <body>
    <h1 id="myElement">this is a heading</h1>
    <p id="p">this is a pragraph, thanks</p>
    <div class="container">
      <div class="items-1 item">item 1</div>
      <div class="items-2 item">item 2</div>
      <div class="items-3 item">item 3</div>
      <div class="items-4 item">item 4</div>
      <div class="items-5 item">item 5</div>
    </div>
    <button id="btn">click me</button>
    <script src="index.js"></script>
  </body>
</html>

Answer №1

To access elements, use their respective IDs or TagNames as shown in the comments and updated code snippet below.

const element = document.getElementById("myElement"); // accessing element by its ID //
element.style.color = "blue";
element.style.backgroundColor = "black";
element.style.fontSize = "80px";
let button = document.getElementsByTagName("button")[0]; // accessing tag by its TagName //
button.style.color = "red";
let paragraph = document.getElementsByTagName("p")[0]; // accessing tag by its TagName //
paragraph.style.backgroundColor = "black";
paragraph.style.color = "green";

Answer №2

Initially, it is important to understand that each ID should be associated with only one HTML element. This ensures uniqueness and prevents confusion when using the getElementById method. To target a specific element, you can utilize querySelector for individual elements and querySelectorAll for multiple elements using the following selectors:

  1. Use # to reference an element by its Id.
  2. Apply . to reference an element by its Class.
  3. Simply state the element's name to refer to it by the HTML tag.

For instance:

// Adjust all divs to have dimensions of 300x150 with borders
document.querySelectorAll('div').forEach(e => {
  e.style.width = '300px';
  e.style.height = '150px';
  e.style.border = '1px solid #000';
});

// Apply specific styles to a particular element
document.querySelector('#div_1').style.background = '#e8e8e8';

// Set font family for all elements with class elem to be serif
document.querySelectorAll('.elem').forEach(e => {
  e.style.fontFamily = 'serif';
});
<p class="elem">Lorem Ipsum</p>
<div class="elem" id="div_1">This is div 1</div>
<div class="elem" id="div_2">This is div 2</div>

P.S. It's essential to note that querySelectorAll should not be employed when referencing multiple elements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through a sequence of URLs in Node.js, one by one

I am new to node js and experimenting with creating a web scraping script. I've received permission from the site admin to scrape their products as long as I make less than 15 requests per minute. Initially, my script was requesting all URLs at once, ...

javascript implementing number formatting during keyup event

When I try to format a number in an input field on the keyup event, I receive a warning in my browser console that says "The specified value "5,545" cannot be parsed, or is out of range." The value in the input field also gets cleared. How can I solve this ...

Conceal div elements containing identical information by utilizing jQuery

I'm dealing with a webpage that pulls in a long section of divs from another application. Unfortunately, I can't filter the divs before they appear, but I urgently need to hide any duplicate data within certain values using jQuery. The duplicate ...

JQuery selector is unable to locate element when passing Span Id

I've been researching and I believed this solution would be effective, but it seems that I made a mistake. The issue involves using Ajax Manager within a function. Here is my Javascript: function makeGetRequest2(wordId, docId) { var ajaxManager ...

Smooth scrolling feature for Wordpress websites

I am currently in the process of converting an HTML5 template into a Wordpress theme. One specific feature I'd like to add is a custom scroll for Wordpress using the code: <script src="jquery.nicescroll.js"></script> DEPENDENCIES This cod ...

jQuery Toggle and Change Image Src Attribute Issue

After researching and modifying a show/hide jQuery code I discovered, everything is functioning correctly except for the HTML img attribute not being replaced when clicked on. The jQuery code I am using: <script> $(document).ready(function() { ...

The table on the page shifts position when viewed on different devices, sometimes not remaining between the header and footer

Here is a link to see how my page looks with the header, table, and footer: https://i.sstatic.net/U6tdO.png If you want to see how it looks when responsive (with smaller width), check out this link: https://i.sstatic.net/zsGkc.png I have encountered 2 ma ...

Instructions on deploying static files to Vercel including HTML, CSS, and JavaScript files

I have encountered an issue and would like to share my solution - please see my initial response. Currently, I am facing a challenge while trying to deploy a repository from my GitHub account. The repository consists of various static files: ├─js ...

A guide to securely retrieving data from the Hono API endpoint using type safety within a Next.js application

Currently, I am using Hono as my API endpoint with Bun. Now, I am working on a new app with Next.js and I want to ensure type safety when fetching data from my API. I believe I can accomplish this through RPC. However, I am unable to locate AppType mention ...

In IE8, submitting an Ajax request almost always results in an error being

This piece of code seems to be causing some trouble, as it works fine in all browsers except for IE8 on an XP machine. No matter what I try, the error function keeps getting triggered specifically in IE8. I've experimented with different dataTypes lik ...

Ensure the website is able to adjust its size when the top banner increases in size

On my website, there is a top banner containing contact information that expands when clicked. However, the expanded div overlaps the site content. Is there a way to make the site scale with the expanded div so that the top of the site starts below it? I ...

Issue with transition not functioning properly on a rotated CSS3 element

Having a bit of trouble with my CSS class: .rotate { -webkit-transition: all 2s ease-in-out; -webkit-transform : rotateY(360deg); } When I change the rotation to 180deg and apply the class using jQuery, the div rotates instantly instead of over a 2 s ...

The navigation bar is not extending to fill the entire width of the screen

I recently created a navigation bar using the nav tag and applied CSS to set the width, border, and padding. However, I noticed that there are some empty pixels on each side of the navigation bar that I can't seem to fill up. Here is the HTML code for ...

The Navbar's Toggle Icon Causes Automatic Window Resize

I implemented a mobile navigation bar using React and JS that slides in from the left when clicked. However, I encountered two issues: whenever I click on a menu button in the navbar or when my ad carousel moves, the window resizes for some reason. Additio ...

Encountering issues with ASP.NET WebAPI: When using $.ajax, a 404 error occurs, while using $.getJSON results in an Uncaught

Currently, I am developing an ASP.NET web API with a C# project that I am attempting to call from JavaScript. Below is the snippet of my JavaScript code: function LoadGraph() { var file = document.getElementById("file-datas"); if ('files' in fi ...

Create a form in a React component that allows the user to input information

My challenge is to create a functionality where each time the add button is clicked, it should dynamically add an input field that I can save. It's similar to this example, but with inputs instead. The complexity arises from the fact that the inputs a ...

The calculator I designed using HTML, CSS, and JavaScript is experiencing difficulty adjusting to various screen sizes

I recently built a calculator using HTML, CSS, and JavaScript. It works perfectly on PC or big screens, but when viewed on smaller devices like phones or tablets, the display gets cut off and does not adjust properly. Here are some example pictures for ref ...

Execute iMacros Loop and terminate the process before proceeding to the next command

As a newcomer to the world of iMacro scripting, I am struggling with setting up a simple data scrape. I'm looking for guidance on how to create a loop for the following commands: URL GOTO=link1 URL GOTO=link2 URL GOTO=link3 WAIT SECONDS=7.5 Once th ...

Navigational menu header leads to specific location on the page

I need the dropdown menu header to both open the related menu and display the content of the first element of the submenu, which is an anchor link on the page. Here is the HTML code for the Dropdown Menu: <div class="collapse navbar-collapse" id="myNa ...

Unfortunately, Safari and iOS do not support the video functionality

I am encountering an issue with my HTML5 sample video not loading in Safari 11 on OSX, but working perfectly fine in Chrome and Firefox. Additionally, the video is not functioning on iOS at all (neither in Safari nor in Chrome). Below is the HTML code: & ...