Javascript returning : "Uncaught TypeError: Cannot read property 'innerText' of null" while typing on search form.
I have a page with some Bootstrap cards, and I want to filter the cards by name. I have tried to get "card-title" element class to validate the search filter.
HTML code:
<div class="container">
<div class="row">
<div class="col-sm-4 mb-4">
<input type="text" id="myFilter" class="form-control" onkeyup="myFunction()" placeholder="Search for card name...">
</div>
</div>
<div class="row" id="myProducts">
<div class="col-md-4">
<div class="card">
<div class="card-header bg-dark d-sm-flex justify-content-sm-between align-items-sm-center">
<div class=" card-title">
<a href="#" style="color:white" class="display-inline- block" onmouseover="this.style.color='#00e6ac'" onmouseout="this.style.color='#fff'">
<strong>Card 1</strong>
</a>
</div>
</div>
<div class="card-body bg-light">
0000x01
</div>
<div class="card-footer bg-white d-flex justify-content-between">
<div>
<i class="icon-arrow-right5 mr-2"></i>Card number one
</div>
</div>
</div>
<div class="card">
<div class="card-header bg-dark d-sm-flex justify-content-sm-between align-items-sm-center">
<div class=" card-title">
<a href="#" style="color:white" class="display-inline- block" onmouseover="this.style.color='#00e6ac'" onmouseout="this.style.color='#fff'">
<strong>Card 2</strong>
</a>
</div>
</div>
<div class="card-body bg-light">
0000x02
</div>
<div class="card-footer bg-white d-flex justify-content-between">
<div>
<i class="icon-arrow-right5 mr-2"></i>Card number two
</div>
</div>
</div>
</div>
<!-- /transparent header, white footer -->
</div>
</div>
Javascript
function myFunction() {
var input, filter, cards, cardContainer, title, i;
input = document.getElementById("myFilter");
filter = input.value.toUpperCase();
cardContainer = document.getElementById("myProducts");
cards = cardContainer.getElementsByClassName("card");
for (i = 0; i < cards.length; i++) {
title = cards[i].querySelector("card-title");
if (title.innerText.toUpperCase().indexOf(filter) > -1) {
cards[i].style.display = "";
} else {
cards[i].style.display = "none";
}
}
}
also testing on: https://codepen.io/pratykus/pen/WNeJpyK
Every time I type on filter box I got incremented error: (6) Uncaught TypeError: Cannot read property 'innerText' of null
When you use .querySelector
you should specify the class or the element
. In your case your element is the div and your class that you're trying to access is card-title
, so change:
title = cards[i].querySelector("card-title");
to:
title = cards[i].querySelector(".card-title");
If you are passing a CSS class as the selector to querySelector()
, then you have to append it with dot .
title = cards[i].querySelector(".card-title");
Make this change to fix the issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.