Use JavaScript to modify the CSS by targeting elements with getElementById

I'm struggling to figure out how to use JavaScript to access a specific CSS.

For example,

#menu { color: red; }

Can be accessed by

document.getElementById('menu').style.color = "blue";

But what if I want to access:

#menu li a { height: 10%; }

Is there a way to do this using document.getElementById()?

Answer №1

Vanilla JavaScript approach:

In this scenario, the usage of getElementById() is not suitable as it is specifically designed to select elements by their id attributes. Instead, you can employ getElementsByTagName() within the context of #menu:

var menu = document.getElementById('menu');
// Retrieve all <li> child elements of #menu
var listItems = menu.getElementsByTagName('li');
// Iterate through each one
for (var i=0; i<listItems.length; i++) {
  // Obtain all <a> child elements of every <li>
  var anchorTags = listItems[i].getElementsByTagName('a');
  for (var j = 0; j<anchorTags.length; j++) {
    // Update their color dynamically
    anchorTags[j].style.color = 'blue';
    // or modify other CSS properties
    anchorTags[j].style.height = '25%'; 
  }
}

Solution using jQuery:

If jQuery is accessible to you, achieving this task becomes much simpler:

$('#menu li a').css('color', 'blue');

Answer №2

In order to achieve this, you would need to locate all the instances of <a> tags that meet the specified criteria.

When it comes to the .getElementById() function, its purpose is to retrieve an element based on a unique "id" attribute. If you are looking to retrieve elements in other ways, there are alternative APIs available such as: .getElementsByTagName(), .getElementsByClass(), .querySelectorAll(), and more. It's important to note that browser support can vary, and the behavior of even .getElementById() differs between Internet Explorer and other browsers.

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

After populating with information, JavaScript turns into an inert void

The issue is that the JavaScript array becomes empty after being filled with values Here is the code I used: var browserdata = new Array(); // Fill the array with values browserdata["qqq"] = "zzz"; browserdata["rrr"] = 1; console.log(browserdata); // T ...

Issues with screen scrolling becoming stuck in React and Material UI

Currently facing an unusual issue where scrolling on my mobile website becomes sticky, with intermittent responsiveness to touch. Struggling to identify the root cause as there are no console errors detected. Provided below is a snippet of code for a subse ...

Determining Text Color Based on Background Hue

Is it possible to create a div that dynamically changes text color based on the background color surrounding it? I want the text to switch between two different colors, with the font color being the opposite of the background color. For example, black text ...

When trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

Error: The function _firebase.db.collection is not defined and cannot be executed

I am a beginner in react-native and JS. Currently, I am working on a chat app project and attempting to implement a button that triggers the creation of a new chat using the provided function: const createChat = async () =>{ await db .collection ...

Can you explain the difference between synchronous and asynchronous loading?

After exploring this website, I have learned that when using CommonJS, the browser loads files one by one after downloading them, which can lead to dependencies slowing down the process. However, with AMD, multiple files can be loaded simultaneously, all ...

What is the most efficient way to minimize the use of if statements in an Angular component when calling a specific function?

Currently, I am working on an Angular 7 temperature conversion application. Within my formGroup, there are inputs and outputs along with two multi-select dropdowns where users can choose the unit of temperature 'From' and 'To' for conve ...

the event listener for xmlhttprequest on load is not functioning as expected

I am facing an issue with validating a form using JavaScript and XMLHttpRequest. The onload function is supposed to display an alert, but it only works sometimes. I'm struggling to identify my mistake. document.getElementById("button").addEventListen ...

Slice an interactive div

I am currently working on setting up a horizontal sliding div for a menu. The layout consists of a left DIV that remains visible at all times, and a sliding DIV that appears horizontally when the menu is activated. My HTML code looks like this. <div id ...

Using express to efficiently redirect from a search form?

As a newcomer to this, my goal is to initiate an external API call after entering a term in a search form and then migrating to a new page displaying the outcomes. Here's what I have accomplished thus far. const express = require('express') ...

Placing divs of varying heights in a circular formation with a specific radius

Recently, I've been attempting to generate a multitude of divs (referred to as bars) and position them in a way that forms a circle in the center. To clarify, here's an example where all bars share the same width and height. Check out the JSFi ...

What could be causing the "undefined class in the imported eval() function" error

Currently, I'm exploring a unique approach to creating a replacer/reviver combination that facilitates the proper serialization and deserialization of ES6 classes for a TypeScript project I am currently developing. To accomplish this, I implemented a ...

Creating dynamic pie charts with animated effects using JavaScript

Looking to develop an interactive pie chart using JavaScript, I delved into some research and stumbled upon the Google Charts API. However, my primary apprehension lies in the fact that the data is transmitted to Google's server for generating the ch ...

Dynamically validate AngularJS forms with JSON Schema

I am currently trying to dynamically validate JSON in AngularJS. Unfortunately, I have encountered an issue with loading fields from the schema onto the page. My understanding of AngularJS is limited as I am still new to it. Although I have managed to cr ...

Inability of Internet Explorer 10 to load resource files

As I work on constructing a website using a combination of HTML5, CSS3, and jQuery, I have encountered an issue when trying to view the page in Internet Explorer X. Despite my efforts to troubleshoot by clearing the cache and adjusting security settings, t ...

Looking for a way to conceal the scrolling content within a div beneath a transparent header? Seeking

This particular question has been asked multiple times, and after careful consideration, I found a solution that closely aligns with my scenario: Hide content underneath a transparent div while scrolling The crux of the issue is that the content div is m ...

Change the flyout menu to activate once clicked instead of when the mouse hovers over

Want to add a cool flyout menu action that triggers on click instead of mouseover? The current code triggers the flyouts on mouseover, but I need them to open only when clicked. Specifically, I'd like to change the functionality so that you click on a ...

Unable to re-focus on div element once the input loses focus

http://jsfiddle.net/NsRyr/1/ I have encountered a puzzling situation. Here's the scenario: I am utilizing a div element (referred to as #keys) to manage keypress events. HTML: <div id="#keys" tabindex="1">Focus</div> JS: $('#keys ...

Steps for handling errors in Node.js when the query result rowCount is 0 and throwing an error in response

If the rowcount is 0, I need to send a response as failed. If the rowcount is 1, I need to send a success status. Can someone please assist me with this? When I try to print (client.query), it displays the result in JSON format (refer to attached image). ...

Is there a way to transform a JSON document into an HTML webpage using Ruby on Rails?

Currently, I am developing a website that is capable of receiving a URL get parameter pointing to a JSON file and transforming it into a visually appealing HTML page (not in table format). To achieve this, I need to create a recursive function for parsin ...