I need your help. I am new to Javascript and jQuery. I have something to do. I have a list of divs with the same class but each div has a specific ID. Let say I have this:
<div class="list" id="apples"></div>
<div class="list" id="bananas"></div>
<div class="list" id="pineapples"></div>
I have the URL https://johndoe.com/apples, https://johndoe.com/bananas and https://johndoe.com/pineapples.
All divs are displayed on the 3 pages but I want to have only the div with id apples displayed on the Apples page and the others to be entirely removed not hidden. I want the same for each page (bananas displayed on bananas' page...). So what I wrote is this. I thought that changing apples div's class to something else would avoid it to be deleted.
var fruitId = val['id'];
function displayDiv()
{
var selectedSection = document.getElementById(fruitId);
if (window.location.href.indexOf(fruitId) > 0)
{
selectedSection.setAttribute('class', 'selectedfruit');
$("div.list").remove();
}
}
Do not pay attention to fruitId it's 'apples', 'bananas' and 'pineapples' in the JSON file and I have the correct list.
Use filter(function) and check the id in the function
$("div.list").filter(function(){
return !window.location.href.includes(this.id)
}).remove();
This will remove only the ones where the id value is not in the href
I tried this and it works perfectly BUT I still have Uncaught TypeError: window.location.href.contains is not a function
$("div.list").filter(function(){
if (window.location.href.indexOf(this.id) > -1)
{
return !window.location.href.contains(this.id)
}
$("div.list").remove();
});
What can I do to remove the error? If I replace the "contains" with "indexOf" then I don't have any results.