I am not familiar with javascript and facing this weird situation.
I am using javascript to iterate over div element and retrieve href values from all <a> element inside, the purpose is to handle click on <a> element by JavaScript instead of default by HTML.
The iteration works but all links target replaced to the last <a> href values.
$(document).ready(function() {
//NavMenu();
//NavActive();
NavClick();
console.log('tes');
});
function NavClick() {
var nav_item = document.getElementById('nav-menu').querySelectorAll('div')
for (let i = 0; i < nav_item.length; i++) {
item = nav_item[i].querySelector('a').getAttribute('href')
nav_item[i].addEventListener('click', function(e) {
e.preventDefault();
$.ajax({
url: item,
contentType: 'application/json',
dataType: 'json',
success: function(data) {
$('title').html(data.title)
window.history.replaceState({}, '', item)
$('#content').html(data.data)
}
});
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="row col-12 justify-content-end" id="nav-menu">
<div class="col-auto">
<a href="/" class="px-1">
Short
</a>
</div>
<div class="col-auto">
<a href="/myurl/' %}" class="px-1">
My URL
</a>
</div>
<div class="col-auto">
<a href="/group/" class="px-1">
My Collection
</a>
</div>
<div class="col-auto">
<a href="/group/create/" class="px-1">
New Collection
</a>
</div>
</div>
What I expecting is my code will add event listener to each element and retrieve the "href" value so I can send request to server with the url.
eg. when I click this link, javascripts will send request to 127.0.0.1 but what i get is request send to 127.0.0.1/group/create/.
<div class="col-auto">
<a href="/" class="px-1">
Short
</a>
</div>
is my logics wrong or I miss something on my codes?
>Solution :
Use let for item:
By declaring item with let, its scope is limited to the block of the loop iteration, avoiding the issue of it being overwritten.
let item = nav_item[i].querySelector('a').getAttribute('href');