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

.htaccess 404 not redirecting properly

I need help with the following code snippet: # Keep this line intact for mod_rewrite rules to function properly RewriteBase / ErrorDocument 404 /errors/404.php Despite having the file 404.php in the errors folder, it doesn't seem to be working as ...

What causes the navbar-brand to be hidden on Chrome mobile browsers?

I recently completed building my website at emdashr.com and have been adjusting the mobile views. However, I'm facing an issue where the navbar-brand disappears when viewing the site on mobile Chrome or desktop Chrome with a small viewport. Interestin ...

What is the procedure for selecting an element based on its child containing specifically filtered text?

Imagine a webpage with the following elements: <div data-search="type1"> any HTML <!-- .click is a child of any level --> <span class="click" data-source="page1.html">blue</span> <!-- let's call it "click1 ...

Hovering over the Instagram icon will reveal a stunning visual effect

I am looking to change the appearance of my Instagram icon when hovering over it. I want the background to turn white and the icon to become colored. Here is my code snippet from Footer.js : <a href="https://www.instagram. ...

Is it possible to insert a button into a specific column of an ngx-datatable within an Angular 8 application?

I am having trouble with this particular HTML code. <ngx-datatable-column name="Option" prop="option" [draggable]="false" [resizeable]="false [width]="250"> <span> <button class="optionButton" type="button" data-to ...

Utilizing timezones with Moment.js

Currently, I am utilizing momemt.js and moment-timezone.js to present time in the browser. At this time, I have received epoch time from the server which has been converted to central time. My goal now is to exhibit the time in EST/EDT format. To achieve t ...

Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature. var fileInput = document.getElementById('jquery-ajax-single') var form = new FormData(); form.append('uploadFile',fileInput.files[0]); $.ajax({ url: "fi ...

Save an automatically generated number into a variable and use it to reference an image file for display. This process can be accomplished using JavaScript

I'm having trouble getting my images to display randomly on a page. The images are named 0 - 9.png and I am using a pre-made function for random number generation. However, when I try to call on this function later down the page, nothing appears. It ...

premature submission alert on button press

I'm encountering an issue where my form is being submitted prematurely when I click on the button. The desired behavior is for the button to create a textarea upon clicking, allowing me to write in it before submitting by clicking the button again. Ho ...

Incorporating jquery-ui in a Rails application does not lead to an error even with a fictional alias

I'm currently working on integrating the jquery-ui-rails gem into my rails application. The app is based on Spree version 3.0. $ bundle list | grep jq * jquery-rails (4.0.5) * jquery-ui-rails (5.0.5) Despite attempting various solutions in the a ...

What is the best way to extract content between <span> and the following <p> tag?

I am currently working on scraping information from a webpage using Selenium. I am looking to extract the id value (text) from the <span id='text'> tag, as well as extract the <p> element within the same div. This is what my attempt ...

What is the best way to bridge the gap between the rows?

After combining the top and bottom blocks, I now have a gap in my layout. Is there a way to move this row up without causing any issues? I need assistance with resolving this problem using Bootstrap. <link rel="stylesheet" href="https://maxcdn.boots ...

Launching a bootstrap modal within another modal

I am facing a minor issue with two modal popups on my website. The first modal is for the sign-in form and the second one is for the forgot password form. Whenever someone clicks on the "forgot password" option, the current modal closes and the forgot pas ...

The validation errors in the form of CodeIgniter are not being displayed by the JavaScript variable

Currently, I am utilizing the built-in validation_errors() function in CodeIgniter for my login form. The validation errors are displaying correctly in my view, but when I try to echo them into a JavaScript variable within the script to customize notificat ...

Utilize the effectiveness of the Ajax Success Handler for retrieving a distinct JSON entity

One of the features I am currently using involves an Ajax command that enables me to query data from a local server. In order to ensure smooth execution, it is crucial for me to return a JSON object through the success handler. The specific structure of m ...

Determine the specific element that triggered an event from a group of elements using Hammer

I am facing an issue with two HTML divs as shown below: <div class="div-class" data-val="1">Div 1</div> <div class="div-class" data-val="2">Div 2</div> <div class="div-class" data-val="2">Div 2</div> When using jQuery ...

Issue with horizontal navigation in CSS

I'm struggling with styling my CSS navigation bar. The last list item is moving to a second line, which really messes up the look of my website. Can someone take a look at my code and point out what I'm doing wrong? Thank you in advance. HTML: ...

Trimming Text with JQuery

My goal was to truncate a string and add an ellipsis at the end using jQuery, but my code doesn't seem to be working as intended. Below is the jQuery code I wrote: $(".link-content > h4").each(function(){ var len = $(this).text().length; ...

How can I load only specific images on a webpage using HTML?

I attempted to implement an image filter for my website by using the code below: <script> function myFunction() { // Initialize variables var input, filter, ul, li, a, i; input = document.getElementById('myInput'); filter = input.value.toU ...

Guide on accessing a local image while setting the background image using JavaScript

I am trying to set a background image from a local source on my computer. Below are two lines of code, one that works and one that does not: (the local one fails) _html.style.backgroundImage = 'url("urlsourceblahblahblah")'; _html.style.backgro ...