Add child element to parent to set of matched elements and use parent Div href - Javascript
I have a situation where I need to add a child div to a set of elements. A child element is a div that has an anchor that takes the href from its parent.
When I did this initially with just one div it was simple enough, but now I'm trying to get it to work with a bunch of elements with a CSS class selector. It seems like I'm just spinning in circles and it's very frustrating :(
Here is the codepen link: https://codepen.io/emilychews/pen/XgrqWZ
Here is the second code to make it look like (this example only has one parent): https://codepen.io/emilychews/pen/RgbawK
Another problem that just came up for me is how can I use it so that each child always takes the href value from the parent when there are multiple instances using the same class?
Any help would be awesome. Emily.
Html
<div class="outerbox">
<a href="https://www.google.co.uk">Here is a job Title</a>
</div>
<div class="outerbox">
<a href="https://www.bbc.co.uk">Here is a job Title</a>
</div>
CSS
* {font-family: arial; color: white;}
body {display: flex; justify-content: space-around;}
.outerbox {
display: flex;
justify-content: center;
align-items: center;
width: 250px;
height: 200px;
background: red;
position: relative;
padding: 20px;
box-sizing: border-box;
}
.outerbox a {margin-right: auto; margin-bottom: auto;}
.innerbox {
background: blue;
position: absolute;
padding: 15px 30px;
}
.innerbox a { text-decoration: none;}
Js
// DECLARE OUTERBOX
var outerbox = document.querySelectorAll('.outerbox');
// GET PARENT ELEMENT HREF ATTRIBUTE
var parentLink = document.querySelectorAll('.outerbox a');
for (var i = 0; i < parentLink.length; i+=1) {
var innerHREF = parentLink[i].getAttribute("href");
}
// CREATE INNERBOX
var innerBox = document.createElement('div');
innerBox.classList = "innerbox";
// CREATE ANCHOR LINK AND PASS IN HREF VAR
var anchorTag = document.createElement('a');
anchorTag.setAttribute("href", innerHREF); // pass in innerHREF var
anchorTag.appendChild(innerHREF);
anchorTag.innerHTML = "Apply";
for (var j = 0; j = innerbox.length; j+=1) {
innerbox[j].appendChild(anchorTag)
}
// ADD INNERBOX TO OUTERBOX
outerbox.appendChild(innerBox);
source to share
your javascript has some errors, try this
<script>
document.querySelectorAll('.outerbox').forEach(function(element){
//get parent link
//var innerHREF=element.querySelector('a').href;
//you need no var, i put it direct on line marked with //*****
//create innerBox
var innerBox = document.createElement('div');
innerBox.classList.add('innerbox');
// CREATE ANCHOR LINK AND PASS IN HREF VAR
var anchorTag = document.createElement('a');
anchorTag.setAttribute("href", element.querySelector('a').href); //***
anchorTag.innerHTML = "Apply";
innerBox.appendChild(anchorTag);
element.appendChild(innerBox);
});
</script>
source to share