Assign a class to the "li" element containing an "a" tag with the specified href attribute

Is it possible to transform the "href" attribute of an element into a class or id like "li" for better css handling?

<ul>
    <li><a href="#section3"><span class="fp-sr-only">due</span><span></span></a><div class="fp-tooltip fp-right">due</div></li>
    <li><a href="#section4"><span class="fp-sr-only">due</span><span></span></a><div class="fp-tooltip fp-right">tre</div></li>
    <li><a href="#section5"><span class="fp-sr-only">quattro</span><span></span></a><div class="fp-tooltip fp-right">noBar</div></li>
</ul>

In other words, can we change the structure to:

<ul>
    <li class="section3"><a href="#section3"><span class="fp-sr-only">due</span><span></span></a><div class="fp-tooltip fp-right">due</div></li>
    <li class="section4"><a href="#section4"><span class="fp-sr-only">due</span><span></span></a><div class="fp-tooltip fp-right">tre</div></li>
    <li class="section5"><a href="#section5"><span class="fp-sr-only">quattro</span><span></span></a><div class="fp-tooltip fp-right">noBar</div></li>
</ul>

If you know a solution, please share. Thank you!

Answer №1

Is it possible to take the "href" attribute of an element and treat it like a class or id of "li" in order to style it with css?

Yes, you can achieve this using attribute selectors and jQuery's closest() method like so:

$('a[href="#section4"]').closest('li').css('background-color', 'green');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <a href="#section3">
      <span class="fp-sr-only">due</span>
      <span></span>
    </a>
    <div class="fp-tooltip fp-right">due</div>
  </li>
  <li>
    <a href="#section4">
      <span class="fp-sr-only">due</span>
      <span></span>
    </a>
    <div class="fp-tooltip fp-right">tre</div>
  </li>
  <li>
    <a href="#section5">
      <span class="fp-sr-only">quattro</span>
      <span></span>
    </a>
    <div class="fp-tooltip fp-right">noBar</div>
  </li>
</ul>

Answer №2

To easily style elements based on specific attributes, you can utilize a CSS attribute selector:

[data-key="section3"] {
    // your styles here
}

Another approach is to generate IDs dynamically using jQuery by extracting the href attribute:

const linkID = $('a').attr('href');
$('a').attr('id', linkID);

Answer №3

The functionality you are seeking is a parent selector, but unfortunately it has not been implemented yet. Once you have selected the <a /> element, navigating back up the DOM structure is not supported. Here are some alternatives to achieve your desired outcome:

  • Apply CSS directly to the anchor elements
  • Explore options for adding classes to the list element through the backend
  • Utilize JavaScript to dynamically add classes to the list element, as mentioned in an earlier response

Answer №4

$('ul li a').each(function(i)
    {
       var href = $(this).attr('href'); // Grab the rel value
       var clsname = href.replace("#","");
       console.log("href",clsname);
       $(this).parent().attr("class",clsname);
    });
<html class="has-navbar-fixed-top">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="js/test.js"></script>
</head>
<body>
<ul>
    <li><a href="#section3"><span class="fp-sr-only">uno</span><span></span></a><div class="fp-tooltip fp-right">uno</div></li>
    <li><a href="#section4"><span class="fp-sr-only">due</span><span></span></a><div class="fp-tooltip fp-right">tre</div></li>
    <li><a href="#section5"><span class="fp-sr-only">quattro</span><span></span></a><div class="fp-tooltip fp-right">noBar</div></li>
</ul>
</body>
</html>

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

Create a variety of unique objects on the canvas without any repetition or unwanted overlapping

Is there a way to generate objects on a map in a HTML5 Canvas without them overlapping or occupying the same space? I tried checking inside an array to see if the next 20 values are already taken to prevent overlapping, but it didn't work as expected ...

Achieving successful functionality with position:relative in IE9

Having difficulty with the position: relative property in IE9. Check out this demo for reference: <div style="overflow:scroll;height:120px;"> <table id="table" width="100%"> <tr style="position:relative;background-color:#1b72a4;"> ...

What is the best way to navigate through an HTML node tree, including all of its sub elements, when walking through

Do you know of a way to iterate through the entire hierarchy of HTML elements and check each one for attributes and more without using JavaScript? We currently have a JavaScript solution that iterates through each child element and all their descendants. ...

AngularJS object array function parameter is not defined

Recently, I've been honing my AngularJS1x skills by following tutorials on Lynda and Udemy. One tutorial involved creating a multiple choice quiz. To test my understanding, I decided to modify the code and transform it into a fill-in-the-blank quiz. ...

Is your Ajax response suddenly failing to work after the initial attempt?

Describing my predicament: The code snippet below is what I have been using to insert a custom-designed div into my webpage. Initially, the div is successfully added; however, it stops working after the first instance. $('#addanother').click(fu ...

Utilizing the :after pseudo-element for placing text in a specific location

Here's the code I'm working with: div#myImg{ background: url('myimage.png') left top no-repeat; } div#myImg:after{ content: 'TEXT UNDER IMAGE'; margin:0 auto; vertical-align:text-b ...

Can an RMD file access a CSS variable?

In my .Rmd file, I am interested in adjusting the style based on whether it is viewed on a mobile device or not. Checking window width with @media in CSS makes this task simple. Let's consider a scenario where there is a root variable --mobile: 1; ...

Utilizing the Bootstrap grid system to align two div elements in one row, with one centered on the page and the other positioned to

Looking for a solution to align two divs inside a flex container - the first centered horizontally and the second aligned to the right. Requirements: must use bootstrap only. |---------------------------------------------| center ...

What is the best way to ensure that each link displays unique text in a separate div when clicked on?

<aside class="side_article_content"><p id="defaultText">Chakras are explained here.</p> <p id="baseChakraInfo" style="display:none;">Base Chakra details here.</p> <p id="sacralChakraInfo" style="display:none;">Sa ...

How can data be sent to an AJAX request using jQuery?

Every time I attempt to send data through ajax, it doesn't seem to pass the data along. $('#savenew').click(function () { var user = <?php echo $user?>; $.ajax({ type: "POST", url: "actions/sub.php", data: user, su ...

JSONP OpenWeather API

I've been trying to access and retrieve weather data from OpenWeather using their API, but unfortunately, I'm facing some difficulties in getting it to work. It seems like there might be an issue with the way I am fetching the JSON data. To quer ...

Manually adding or removing rows in a DataTable

I've been racking my brain over this issue since yesterday and nothing seems to be working. Here's the problem: I have a table that utilizes DataTables (datatables.net). It needs to be cleared of all rows programmatically and then new rows added ...

Is it possible to iterate through div elements using .each while incorporating .append within an AJAX call?

After sending AJAX requests and receiving HTML with multiple div elements (.card), I am using .append to add new .card elements after each request, creating an infinite scroll effect. However, I am facing issues when trying to use .each to iterate over all ...

Align the bottom borders to the lowest content on each line

I am working on designing my homepage using HTML, CSS, JSP, and JavaScript, focusing on the sale of musical instruments and facilitating communication among users. Right now, I am in the process of creating a site-map for my menu configuration chart using ...

Strange gray gradient background suddenly showing up on mobile devices

Encountering an issue with a login form displayed on a sliding modal. The design looks correct on desktop and even in responsive mode with dev tools, but when accessed through mobile Chrome or Safari on an iPhone, an unusual gray rounded box or shadow appe ...

Ways to receive notification during the user's selection of an option by hovering over it

Is there a way to receive an event when a user hovers over a select option? I thought that using the onMouseOver or onDragOver props on the option component would work, but it seems like they only trigger for the parent select component. Below is a simpli ...

Error: Code cannot be executed because the variable "sel" has not been defined in the HTML element

Every time I try to click on the div, I encounter an error message stating 'Uncaught ReferenceError: sel is not defined at HTMLDivElement.onclick' I am currently developing with Angular 8 and this error keeps popping up. I have read through simil ...

How to retrieve a variable from an object within an array using AngularJS code

I recently started learning TypeScript and AngularJS, and I've created a new class like the following: [*.ts] export class Test{ test: string; constructor(foo: string){ this.test = foo; } } Now, I want to create multiple in ...

Resolving syntax error to enable dismissible device alerts

I am attempting to make my devise alerts dismissible. According to the bootstrap documentation found at this link, adding data-dismiss="alert" is necessary. However, when I try to implement this into my application layout as shown below, a syntax error oc ...

Tips on keeping a div element in a fixed position until triggered by jQuery

I've managed to create a navigation bar within a header that sticks to the top of the screen once you scroll down past 100px. The functionality works well, but I'm looking to make the navigation bar stay fixed on the right until it snaps, essenti ...