I am trying to add different links href
depending on what the id
of the div
is.
The a
elements are added via jQuery.
I have tried with
$id = document.getElementsByClassName("content-box")[0].id;
But then I don't know how to do the switch-case
. I can't figure out how to retrieve all the ids.
How can I solve this?
$link = "#";
$id = "";
switch($id){
case "box-1":
$link = "https://www.google.com/";
break;
case "box-2":
$link = "https://stackoverflow.com/";
break;
case "box-3":
$link = "https://www.apple.com/no/";
break;
}
jQuery( '.container h2' ).after(
'<a href="'+ $link +'" id="button-order">Read more</a>'
);
.container {
display: flex;
}
.content-box {
width: 30%;
height: 100px;
border: 1px solid #000;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div id="box-1" class="content-box">
<h2>Title 1</h2>
</div>
<div id="box-2" class="content-box">
<h2>Title 2</h2>
</div>
<div id="box-3" class="content-box">
<h2>Title 3</h2>
</div>
</div>
Use:
$id = document.getElementsByClassName("content-box")[0].id;
It only references the element at index 0
of the HTMLCollection
returned by .getElementsByClassList
.
You can use an iterator for the classList
within a for
or for..of
loop, to reference the current element at index N of the HTMLCollection
and get the id
of that element to pass to switch
, substitute .insertAdjacentHTML()
with "beforeend"
set as the first parameter and HTML string at the second parameter.
for (let box of document.getElementsByClassName("content-box")) {
let $link = "#";
const $id = box.id;
switch ($id) {
case "box-1":
$link = "https://www.google.com/";
break;
case "box-2":
$link = "https://stackoverflow.com/";
break;
case "box-3":
$link = "https://www.apple.com/no/";
break;
}
box.insertAdjacentHTML("beforeend"
, '<a href="' + $link + '" id="button-order">Read more</a>');
}
.container {
display: flex;
}
.content-box {
width: 30%;
height: 100px;
border: 1px solid #000;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div id="box-1" class="content-box">
<h2>Title 1</h2>
</div>
<div id="box-2" class="content-box">
<h2>Title 2</h2>
</div>
<div id="box-3" class="content-box">
<h2>Title 3</h2>
</div>
</div>
Alternatively
for (let boxes = document.getElementsByClassName("content-box"), i = 0
; i < boxes.length; i++) {
let $link = "#";
const box = boxes[i];
const $id = box.id;
// same code at `for..of` loop
}