Home > Net >  Get href from child element and wrap parent element with a linked overlay
Get href from child element and wrap parent element with a linked overlay

Time:10-15

Starting with this:

<div >
<div >
<a href="link1"></a>
</div>
</div>
</div>

<div >
<div >
<a href="link2"></a>
</div>
</div>

<div >
<div >
<a href="link3"></a>
</div>
</div>

What I am trying to achieve:

<div >
<a href="link1" >
<div >
<a href="link1"></a>
</div>
</a>
</div>

<div >
<a href="link2" >
<div >
<a href="link2"></a>
</div>
</a>
</div>

<div >
<a href="link3" >
<div >
<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>' );
    });

CodePudding user response:

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)
    });
 

CodePudding user response:

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 >
<div >
<a href="link1">Link 1</a>
</div>
</div>

<div >
<div >
<a href="link2">Link 2</a>
</div>
</div>

<div >
<div >
<a href="link3">Link 3</a>
</div>
</div>

  • Related