Retrieve the id of an element and a standard element using JavaScript

I have a CSS selector

#menu li {background-color: red;}
.

I'm trying to retrieve its properties using JavaScript. It's crucial for me to access both the #menu and li elements separately as they have distinct attributes. Unfortunately, methods like

getElementById(menu li), QuerySelector and getComputedStyle
don't seem to be effective in this particular scenario.

Is there an alternative approach I can take or is there something I may be overlooking?

Answer №1

To tackle this task, it is recommended to utilize jQuery. Below is a straightforward code snippet for your reference:

//html
    <div id="menu" data-number="123">
    </div>
//jquery
    var menu = $('#menu').attr('data-number');
    console.log(menu);
    //output: 123

Answer №2

Looking at different versions

https://jsfiddle.net/pn52uvw1/

$(".button_1").click(function(){
    alert($("#menu").attr("data-item-id"));
})
$(".button_2").click(function(){
    alert($("#menu li").attr("data-item-id"));
})

Comparing without jQuery

https://jsfiddle.net/pn52uvw1/2/

window.firstFunction =  function(){
    var target = document.getElementById("menu");
    alert(target.getAttribute('data-item-id'));
}

window.secondFunction =  function(){
    var target = document.getElementById("menu").children[0];
    alert(target.getAttribute('data-item-id'));
}

To iterate through multiple items, consider removing the [0] index and utilize a loop or similar method

Answer №3

To retrieve the property of a CSS rule, follow these steps:

function getStyleFromSelector(selector, styleName) {
    // Locate all style elements
    var styles = document.styleSheets;
    var styleIndex = 0, styleCount = styles.length;
    var rules, ruleCount, ruleIndex;
    // Iterate through styles
    for (styleIndex = 0; styleIndex < styleCount; ++styleIndex) {
      
      // Fetch the css rules under the style.
      rules = styles[styleIndex].rules;
      ruleCount = rules.length;
      for (ruleIndex = 0; ruleIndex < ruleCount; ++ruleIndex) {
        
        // Check if the selector matches the desired one
        if (rules[ruleIndex].selectorText === selector) {
          return styleName ? 
              rules[ruleIndex].style.getPropertyValue(styleName) : rules[ruleIndex];
        }
      }
    } 
}

var div = document.getElementById("results");
var result = getStyleFromSelector('#menu li');
console.log(result);
div.innerHTML = 'background-color is : ' + result.style.backgroundColor;
console.log(getStyleFromSelector('#menu li', 'background-color'));
#menu li {background-color: red;}
<div id="results"></div>

Answer №4

If you want to give it a shot without relying on extra libraries, here's how you can do it:

var totalItems = document.querySelectorAll("#menu li").length;
for(j = 0; j<totalItems; j++)
    document.querySelectorAll("#menu li")[j].style.backgroundColor="blue";

I even created a (not-so-pretty) jsfiddle for you to check out

https://jsfiddle.net/gmeewsmz/

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

Guide on integrating the @nuxtjs/axios plugin with Nuxt3

I'm trying to fetch API data from using this code: <template> <div> </div> </template> <script> definePageMeta({ layout: "products" }) export default { data () { return { data: &apo ...

Struggling with my jQuery Ajax call, need some help

I am attempting to create an ajax request that will update the content of my select element. Below is the code for my request : $(function() { $("#client").change(function() { type: 'GET', url: "jsonContacts. ...

Troubleshooting problem with event triggering in Angular's ngSelect dropdown menu items

Hello, I am currently utilizing ngSelect but encountering an issue. Whenever a user hovers over an option in ngSelection, I would like to trigger an event that is created in my typescript file. I am using Angular 13, so I am unsure how to achieve this. Is ...

Initializing Angular variables

My Angular controller has a variable called $scope.abc. The backend I'm using is Sails. The initial value of $scope.abc can be set by the backend when the page is first generated. Once the page is displayed, the user may or may not change this value ...

Is it possible to target a specific element within one of two classes that share the same name using CSS or XPath in Webdriver.IO?

Currently, I am using Webdriver.io and facing a challenge in selecting an element within the "text-fields-container" class. This particular element happens to be a password field, and both classes share the same name. Can someone guide me on how to go abou ...

What are the best scenarios for implementing jQuery-ui plugin as opposed to Backbone View?

I am feeling uncertain about the concept of "componentization" in web UI development. When I need a component, should I develop my own jQuery-UI plugin or opt for creating a MarionetteComponent if I am using Backbone.Marionette? Both options provide reusa ...

Applying drop cap styles to generated content in pseudo-elements

In my blogging Q&A section, I wanted to add a unique touch by starting each question with a large question mark and each answer with a large exclamation mark as a drop cap. I tried using the ::first-letter pseudo-element along with the initial-letter prope ...

Implementing form validations using JavaScript for a form that is created dynamically

I have dynamically created a form using javascript and now I need to add mandatory validations on the form. The validations should trigger when the dynamically created button is clicked. However, I am facing an issue where I receive an error whenever I t ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

Verify if the expression can be found in the DIV element's style

Recently, I encountered a situation where a DIV contains a background image that is either set directly or generated as an SVG. I needed to figure out how to determine when the DIV contains the SVG-string. Here are my two DIVs: <div class="cover m ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

Switching the background color of alternating divs in reverse order: a step-by-step guide

I am looking to alternate the background color of divs between odd and even, with the last div being grey and the second to last div being green. I have tried using the odd/even classes in CSS, but it did not work as expected. .main{ width:500px; height ...

"How to Develop an Eraser Tool Using EaselJs - Exploring Further Possibilities

Currently, I am working on creating a Bitmap eraser on easelJS. I feel like I've made significant progress towards achieving this goal, but I'm still a bit unsure of the next steps... Here is a demo of my progress so far: http://jsfiddle.net/bor ...

What are the benefits of keeping synchronous state in the Redux store?

Is it necessary to store non-async state in the Redux store? For instance, when dealing with a modal that simply shows or hides, is it worth the extra work to toggle it within the store? Wouldn't it be simpler to just keep it as local state in the Rea ...

What is the alternative method of invoking a function within another function in React Native without utilizing a constructor?

Within my RegisterTaster function, I need to execute another function called endRegisterAlert. Since I'm not using a constructor and instead treating the class as a const in React Native, how can I achieve this? What is the best way to call the endRe ...

The div's height is being disrupted by the accordion

Currently, I am facing an issue with the accordion component in Angular and ng-bootstrap. The problem arises when I place an accordion within a div that has a specified max-height. The accordion extends beyond this height limit, whereas I would like it to ...

Having trouble installing the @mui/x-data-grid package in a React project

npm install @mui/x-data-grid encounters a problem that throws an error message: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

What could be the reason for incorrect data being sent when using multi-select values with jQuery/A

I implemented a multi-select dropdown menu where users can select values. Whenever a user selects a value, a jQuery/AJAX request is sent to the server. Check out the code snippet below: $("#send").on("click", function() { var elem$ = $("#cars"), el ...

What is the correct way to retrieve a JSON object instead of getting [Object object]?

Creating a basic web scraper integrated with mongoDB. Even though the API returns the JSON object in the correct format, when trying to append it to a bootstrap card on the page, I'm getting [Object object]. Below is my JavaScript code running on th ...

Reducing image size using CSS can result in blurry images on multiple web browsers

Encountering challenges with downscaled images in multiple browsers... The images must be downscaled to adapt to the browser size. Here is the code snippet: #pic-holder img { -moz-transform: rotate(0deg); /*image-rendering:-webkit-optimize-contras ...