utilize jQuery to include a tag into every div

This is the current sample:

<div class="main-wrap">
    <div class="inner-wrap">
        some example text here
        <span>
           <a href="1">test1</a>
        </span>
    </div>

    <div class="inner-wrap">
      some example text here
      <span>
        <a href="2">test2</a>
      </span>
    </div>

    <div class="inner-wrap">
      some example text here
      <span>
         <a href="3">test3</a>
     </span>
    </div>
 </div>

I want to retrieve the href attribute of each a tag inside the span tag and add it to the entire inner-wrap element. Here's an expected outcome:

<div class="main-wrap">
    <div class="inner-wrap">
      <a href="1">
        some example text here
        <span>
           <a href="1">test1</a>
        </span>
      </a>
    </div>

    <div class="inner-wrap">
     <a href="2">
      some example text here
      <span>
        <a href="2">test2</a>
      </span>
     </a>
    </div>

    <div class="inner-wrap">
     <a href="3">
      some example text here
      <span>
         <a href="3">test3</a>
     </span>
    </div>
   </a>
 </div>

I am able to extract the href attribute of each a tag but I'm struggling with how to insert it into the respective inner-wrap divs. This is my current progress:

$('.inner-wrap').each(function(){
    $this = $(this);
    $fetchLink = $this.children('span').find('a').attr('href');
    console.log($fetchLink);
});

Although this task might seem simple, I'm unable to find a solution on my own. Any assistance would be appreciated.

View the functioning jsfiddle demo

Answer №1

If you want to wrap content using wrapInner(), make sure not to nest an anchor tag inside another anchor element.

$('.inner-wrap').wrapInner(function(i) {
  var $this = $(this);
  var a = $this.children('span').find('a');
  var href = a.attr('href');

  //Remove inner anchor
  a.replaceWith(a.text());

  return "<a href='" + href + "'></a>";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-wrap">
  <div class="inner-wrap">
    some content here
    <span>
           <a href="1">test1</a>
        </span>
  </div>

  <div class="inner-wrap">
    some content here
    <span>
        <a href="2">test2</a>
      </span>
  </div>

  <div class="inner-wrap">
    some content here
    <span>
         <a href="3">test3</a>
     </span>
  </div>
</div>

Answer №2

Although it may not be the most efficient solution, the concept here involves replacing the $.html() of .inner-wrap with the same content wrapped in an a tag where the $fetchLink is used as the href attribute.

$('.inner-wrap').each(function() {
  $this = $(this);
  $fetchLink = $this.children('span').find('a').attr('href');
  $this.html('<a href="'+$fetchLink+'">'+$this.html()+'</a>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-wrap">
  <div class="inner-wrap">
    some content here
    <span>
           <a href="1">test1</a>
        </span>
  </div>

  <div class="inner-wrap">
    some content here
    <span>
        <a href="2">test2</a>
      </span>
  </div>

  <div class="inner-wrap">
    some content here
    <span>
         <a href="3">test3</a>
     </span>
  </div>
</div>

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

Switching images upon hovering in AngularJS

Looking to change images on hover in my Angular app, encountered site peculiarities making CSS solution impractical. Resorted to using ng-mouseenter and ng-mouseleave for image swapping instead. landing.jade img.share-button(src='images/btn_share.p ...

Conceal a div once the user scrolls to a certain position using vanilla JavaScript

As a beginner in the field of web development, I am currently working on creating a blog website. Code Function - One of the challenges I'm facing is implementing a floating pagination bar that needs to be hidden when a visitor scrolls near the foote ...

Retrieve the numerical worth of a specific offspring component

I am currently working with the following HTML structure: <td class=​"prd-var-price"> ​<div class=​"price-total">​ <span class=​"price-unit">​€​</span> ​<span class=​"price-value">​ ...

Setting a variable equal to user input

When using a jQuery script, the elements for the details are dynamically created inside a jQuery function. However, there seems to be an issue with assigning the value from the variable "startLocation" to the input "detail_startLocation[]". Only the firs ...

Transform the jquery array into JSON format and transmit it via ajax communication

My array looks like this info['mk'] = 'hi'; info['pk'] = 'hello'; info['wk'] = 'hi'; info['rk'] = 'hello'; Can I convert it to JSON and send it using AJAX? ...

Vue component architecture

Just started exploring Vue last night, so the answer might be obvious. I came across components with this layout: <template> <Slider v-model="value"/> </template> <script> import Slider from '@vueform/slider' ...

Restricting the amount of SQL results displayed

Currently, I am facing an issue with my load.php page where it is supposed to display six results from a specific position in the table based on a position variable. However, nothing is being returned and I suspect there might be a mistake in the code. Cou ...

Make sure that your inline-block elements are aligned with both the left and right edges of their

Explaining what I'm attempting can be a bit tricky, but I'll do my best. I have X number of categories that I need to organize. Each category needs to be enclosed in a box with a grey border. I want the category boxes to be displayed "inline-bl ...

Verify if a certain value exists in an array while using ng-if inside ng-repeat

Currently, I have a loop using ng-repeat that goes through a list of wines obtained from an API. Alongside this, there is an array variable containing all the IDs of wines that have been marked as favorites and retrieved from the database. My goal is to sh ...

Retrieve the page dimensions from a Material UI component `<DataGrid autoPageSize/>`

When utilizing <DataGrid autoPageSize/>, as outlined in the documentation, you can have a Material UI table that adjusts its page size based on the browser height. However, if you are fetching data from the server progressively, it becomes essential ...

When I try to share a link to my website on Google Plus, the thumbnail does not appear

Previously, I encountered a similar issue on Facebook, but by utilizing the following tag, I was able to resolve it: <meta property="og:image" content="link to image" /> The dimensions of the image in the "link to image" are 200px x 200px, which me ...

The chart is failing to update with the data it obtained through Jquery

Scenario: I want to populate a chart using data fetched by Jquery. $.getJSON("/dashboard/", function(data, status) { var test_data=data console.log(test_data) chart.data.datasets[0].data=test_data; ...

Implementing a callback function in Vue js 2 for handling dispatched actions within a component

Is there a method to determine if the action dispatched from a component has completed without utilizing state management? Currently, I have an action called createAddress. In my component, there is a modal where users input their address. Once the user en ...

Is CSS General sibling selector not functioning properly when used with :focus?

How can I display text that turns into an input form when hovered over, and stays visible even if it's unhovered but the user is interacting with the input form? The issue is that when the input form is focused while unhovered, both the input form an ...

Unexpected result when trying to return a value from a recursive function

Attempting to solve the problem of calculating the number of ways a number can be decoded, with 1 as a, 3 as c, and 26 as z. The function seems to calculate the correct count, but for some reason only returns undefined. It appears that the recursive calls ...

Using PHP and jQuery to display or conceal a div based on user login status

UPDATE: I truly appreciate all the feedback and responses. Even after removing the JavaScript and relying solely on PHP if/else statements, I am still encountering the same issue. I repeatedly come across the following error: Both of the following divs ...

Integrate an item into the request body utilizing the $.load() function in jQuery

Currently, I am using a POST request via jQuery's $.load function to retrieve data to display in a window. This is what I am currently doing: var testObject = { thing1: 'data1', thing2: 'data2', thing3: &a ...

retrieve the path of any module within an npm monorepo

I am working on a project using an NPM monorepo structure which utilizes ECMAScript Modules (ESM): <root> |_package.json |_node_modules/ | |_luxon (1.28.0) |_packages/ |_pack1 | |_node_modules/ | | |_luxon (3.0.1) | |_main.js |_pack2 |_ ...

Unable to see background image inside div

Why is the background image not showing up in the left column? I've applied the CSS background-image to .left but it's still not working. Any suggestions on what might be causing this issue? It seems like a small problem, but it's really bot ...

Verifying the current password and updating the hashed password

I have been struggling with creating a PHP script for updating user hashed passwords. Unfortunately, the script is not functioning as expected and no error messages are being displayed. Every time, it only shows "Your old password is incorrect" message. I ...