Using Jquery to locate a specific data element

I have the code snippet below:

<div id="mainMenuInternalMyProfile" class="mainMenuInternalTab" data-pagename="myprofile">
  <div class="mainMenuInternalTabClickable">&nbsp;</div>
    <h4 class="mainMenuInternalTitle">MY PROFILE</h4>
    <img src="images/main-menu-divider.png" class="mainMenuBackGroundDivider" alt="Dating Internal Menu Background Divider">
    <img src="images/main-menu-selected.png" class="mainMenuBackSelected mainMenuBackSelectedOption" alt="Dating Internal Menu Selected">
  </div>

The first line in the code contains data-pagename="myprofile". Similar HTML chunks exist with different data-pagename attributes.

I want to identify and modify elements that match a specific data-pagename value such as 'home' or 'myprofile'. Below is my attempt using jQuery:

var element = $('div.mainMenuInternalTab').find("[data-pagename='" + urlType + "']");
element.css({'color': '#000000','z-index':'100'});

I am uncertain about the correctness of my approach.

Should I target a higher-level parent DIV with an ID instead of using $('div.mainMenuInternalTab') which has multiple instances?

Please advise, additional information can be provided if necessary.

Answer №1

Could it be this solution?

$('div.mainMenuInternalTab').each(function() {
  var element = $(this).find("[data-pagename='" + urlType + "']");
  element.css({'color': '#000000','z-index':'100'});
}

Alternatively, we could consider creating a specific classname for the color and zIndex:

element.toggleclass("black");

UPDATE

Upon further examination, I see you identify the div first and then search for a data-pagename within the same div. Could it mean something like this?

$('div[data-pagename="' + urlType + '"]').each(function() {
  $(this).css({'color': '#000000','z-index':'100'});
}

Or perhaps even simpler:

$('div[data-pagename="' + urlType + '"]').css({'color': '#000000','z-index':'100'});

Answer №2

Give this a shot

element = $('div.headerTab[data-tabname="' + tabType + '"]');

OR

element = $('div.headerTab').filter('[data-tabname="' + tabType + '"]');

By using .find(), you will specifically look for elements that are children of the div .

However, the data attribute belongs to the div itself. Therefore, it should be excluded.

You can also string together your selector

$('div.headerTab').filter('[data-tabname="' + tabType + '"]')
     .css({'color': '#FF0000','z-index':'50'});

Answer №3

The .find() method is not being utilized correctly. You should try the following approach:

HTML

<div id="mainMenuInternalMyProfile" class="mainMenuInternalTab" data-pagename="example1">
    <div class="mainMenuInternalTabClickable">&nbsp;</div>
    <h4 class="mainMenuInternalTitle">MY PROFILE</h4>
    <img src="images/main-menu-divider.png" class="mainMenuBackGroundDivider" alt="Dating Internal Menu Background Divider">
    <img src="images/main-menu-selected.png" class="mainMenuBackSelected mainMenuBackSelectedOption" alt="Dating Internal Menu Selected">
</div>

<div id="mainMenuInternalMyProfile" class="mainMenuInternalTab" data-pagename="example2">
    <div class="mainMenuInternalTabClickable">&nbsp;</div>
    <h4 class="mainMenuInternalTitle">MY PROFILE</h4>
    <img src="images/main-menu-divider.png" class="mainMenuBackGroundDivider" alt="Dating Internal Menu Background Divider">
    <img src="images/main-menu-selected.png" class="mainMenuBackSelected mainMenuBackSelectedOption" alt="Dating Internal Menu Selected">
</div>

jQuery

$(document).ready(function() {
    $(".mainMenuInternalTab").each(function() {
        var _this = $(this);
        var pageName = _this.data("pagename");
        var urltype1 = "example1";
        var urltype2 = "example2";
        if (pageName === urltype1) {
            _this.css({
                "font-size": "5px"
            })
        } else if (pageName === urltype2){
           _this.css({
                "font-size": "25px"
           })
        }
    });
});

In this jQuery snippet, I iterate through all instances of .mainMenuInternalTab, extract their data-pagename attribute and apply specific styles based on its value using simple conditional statements.

You can view a live demo of this implementation here on jsFiddle.

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

Give priority to executing jQuery Ajax before running JavaScript

Is there a way to ensure that alert(1) runs first in this scenario: $.post('example.php', function() { alert(1); }) alert(2); alert(3); alert(4); The jQuery ajax call appears to run asynchronously. This means that Jav ...

Struggling to retrieve dataset from Bootstrap 5 form while using Angular

With the combination of Angular and Bootstrap 5, I have crafted this unique HTML form: <div class="mb-3"> <label for="genreName"> Type name</label> <div *ngIf="!enterTheGenre" class="form-group&qu ...

Adjust the image size to fit the page according to its height

Having a dilemma here. I have this square image (2048x2048) that I want to set as a background. The tricky part is, I want it to display borders when the page stretches into widescreen mode, but also resize while maintaining its square shape when the page ...

Visual Composer now appends "?id=" to the background images of columns and rows, enhancing the customization

I am in the process of improving the performance of a WordPress site that is using the Visual Composer plugin. When checking GTmetrix results, I came across this issue: Ensure resources are served from a consistent URL https://example.com/wp-content/uploa ...

Tips for designing websites using HTML and CSS

current result: https://i.sstatic.net/eXLPv.png desired output: https://i.sstatic.net/vgl6z.png I am aiming to center the text. add image description here add image description here ...

The flex container is expanding larger than its parent container due to the height of its child elements

I have designed the following HTML element. In this case, the remaining-height class is intended to be the remaining height of the container-div, which should be 100 - 15 = 85px. However, because the grand-child-div has a height of 200 px, the remaining-h ...

Ensuring Consistent Item Widths in a Loop using JavaScript or jQuery

In my code, I created a function that dynamically adjusts the width of elements in a loop to match the widest element among them. // Function: Match width var _so20170704_match_width = function( item ) { var max_item_width = 0; item.each(function ...

The menu content has a 50% chance of appearing when the open menu button is clicked

Hey there, I'm currently facing an issue with a menu I created that slides open to the bottom when a button is clicked. The problem I'm encountering is that the content of my menu only appears about half of the time... I'm not quite sure how ...

Tips for adjusting the wrapper css rule of a Tabs component to left-align text in a vertical tab within Material-UI

Typically, when text is placed inside the wrapper, it is aligned in the center. Is there a way to adjust the wrapper rule in <span class="MuiTab-wrapper">Item One</span> so that the tab text is aligned to the left (similar to what w ...

What is the best way to ensure that my top menu remains fixed while scrolling?

Link to website: I am looking to have the top menu on my page remain fixed at the top of the screen as users scroll. Does anyone know if this is achievable, and if so, how can I implement it? ...

What is the best way to transfer information from a client's HTML to a node.js server?

I needed to transmit JSON data to a node.js server. Here is my server.js code: var http = require('http'); var util = require('util') http.createServer(function (req, res) { console.log('Request received: '); util.log(util. ...

Is there a method to play videos automatically without turning off the sound? How exactly does YouTube manage to achieve this feature?

Is there a way to automatically play a video with sound, without the muted attribute? I noticed that when clicking on a YouTube video link, it plays automatically. Looking forward to hearing your thoughts on this! If I can open a YouTube link and have the ...

The `mouseenter` event handler fails to trigger properly on its initial invocation

As I work on a function to remove a CSS class display:hidden; when the mouse enters a specific part of the DOM to reveal a menu, I encounter an issue. Upon loading the page and hovering over the designated area for the first time, the event fails to trigge ...

Getting error specifics from Ajax POST in Rails 4

Is there a way to retrieve detailed error information from a POST request? For instance, when implementing validation like validates :name, presence: true, how can I alert the user if they leave a field blank? .js file: $.ajax({ url: "/warehouses/ ...

Using Python's BeautifulSoup library to pull information from an HTML table

I need help extracting a table from a webpage. Here's the HTML and Python code using beautifulsoup that I've been trying with. It usually works for me, but this time it's coming up blank. Any insights are appreciated! <table> <thea ...

Expansive Offspring Division stretching to the Entire Vertical Length of its Guardian Division

I'm attempting to achieve full coverage of the parent div section by my child div section. Take a look at the Example URL (specifically where the Canadian Flag Stand Up Paddle Boarders are located) towards the bottom: Essentially, when I set the widt ...

Bootstrap 4 radio buttons are not aligning properly with the padding

There seems to be an issue with the alignment of Bootstrap 4 custom radio buttons and my left padding. Here is a snippet: https://i.sstatic.net/vWTNo.png This is part of the code for displaying an item <div class="p-4"> <ul class="d-flex ...

Is it possible to align a CSS table row with its corresponding table header even when the table row is deeply nested within the table structure?

I am looking to keep the structure of my HTML code consistent and unaltered. However, this has resulted in a form tag being nested inside a table row before the table cells can begin. The information I need to display is tabulated data, which makes CSS t ...

Hide the button with jQuery Ajax if the variable is deemed acceptable upon submission

I need to figure out how to hide the submit button if the email entered is the same as the one in the database from action.php. Can anyone help me with integrating this functionality into my existing code? <form onsubmit="return submitdata();"> ...

Trouble with using jQuery's find function when dealing with HTML responses from an AJAX call

I'm attempting to retrieve an HTML webpage using AJAX and then locate a specific div element $.get(url, function (data) { console.log($(data).find("div#container").html()); }); During debugging, I observe $(data) in the console as >> ...