skip to Main Content

Starting with this:

<div class="outside">
<div class="container">
<a href="link1"></a>
</div>
</div>
</div>

<div class="outside">
<div class="container">
<a href="link2"></a>
</div>
</div>

<div class="outside">
<div class="container">
<a href="link3"></a>
</div>
</div>

What I am trying to achieve:

<div class="outside">
<a href="link1" class="overlay">
<div class="container">
<a href="link1"></a>
</div>
</a>
</div>

<div class="outside">
<a href="link2" class="overlay">
<div class="container">
<a href="link2"></a>
</div>
</a>
</div>

<div class="outside">
<a href="link3" class="overlay">
<div class="container">
<a href="link3"></a>
</div>
</a>
</div>

Needs to work if for any number of ".container" divs. I’m guessing I should be putting the inner hrefs into an array but I’m getting stuck on how to insert the values into the overlay wraps.

Here’s one of my attempts:

var arr = $('.container a').map(function() {
    return this.href;
}).toArray();


$('.outside').each(function() {
        .wrapInner( '<a href=' + arr + '></a>' );
    });

2

Answers


  1. Here is a solution with Vanilla JavaScript.
    Create an anchor tag

    let anchor = document.createElement("a")
    

    Get all the elements with className "outside"

    let outside = document.querySelectorAll(".outside")
    

    call a for each for them

        outside.forEach( function(element, index) {
            anchor.classList.add("overlay")
            anchor.setAttribute("href", `link${index+1}`)
            let container = element.children[0]
            anchor.appendChild(container)
            element.prepend(anchor)
            console.log(element.outerHTML)
        });
     
    
    Login or Signup to reply.
  2. You are almost success,just need to using index to get the right link attribute

    enter image description here

    var links = $('.container a').map(function() {
        return $(this).attr("href");
    }).toArray();
    
    
    $(".outside").wrapInner(i => {
      return "<a class='overlay' href='"+links[i]+"'></div>";
    });
    
    // test data
    $(".outside").each((i,e) => {
      console.log("------------------")
      console.log(e.outerHTML)
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="outside">
    <div class="container">
    <a href="link1">Link 1</a>
    </div>
    </div>
    
    <div class="outside">
    <div class="container">
    <a href="link2">Link 2</a>
    </div>
    </div>
    
    <div class="outside">
    <div class="container">
    <a href="link3">Link 3</a>
    </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search