This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 2 years ago.
I am trying to change the text from "yes" to "ok," but get the error: Uncaught TypeError: Cannot read property 'addEventListener' of null.
JS
// create DOM element references
let card1= document.querySelector("div.class-1");
card1.addEventListener("mouseenter", function() {
let text1 = document.querySelector("p.card-text");
console.log(text1);
text1.innerHTML = "Ok";
});
HTML
<div class="col-sm-12 col-md-6 col-lg-4 pb-4">
<div class="card-item card-1">
<p class="card-text">Yes</p>
</div>
</div>
There is no div tag that has .class-1 class. From your html code, you need to find the selector with div.card-1 as follows.
let card1 = document.querySelector("div.card-1");
card1.addEventListener("mouseenter", function () {
let text1 = document.querySelector("p.card-text");
console.log(text1);
text1.innerHTML = "Ok";
});
<div class="col-sm-12 col-md-6 col-lg-4 pb-4">
<div class="card-item card-1">
<p class="card-text">Yes</p>
</div>
</div>
Related
This question already has answers here:
Getting the parent div of element
(7 answers)
Closed last month.
I have a project. I am working to find a container using an only child in JavaScript.
I want to add a class to the container of the req-address.
I want to take req in Javascript using an only child of this element. How to do it?
const search = document.querySelector('.search-form');
const addresses = document.querySelectorAll('.req-address');
search.addEventListener('keyup', function(e) {
addresses.forEach(function(address) {
if (address.innerHTML === search.value) {
address.classList.add('.search-active');
}
});
});
<div class="reqs-container">
<div class="req">
<div class="req-time">
<div class="req-time_from">13:00</div>
<span></span>
<div class="req-time_to">15:00</div>
</div>
<div class="req-restaurant">Argentina Grill</div>
<div class="req-address">Оболонь</div>
<div class="req-name">Аліна</div>
Instagram
Приєднатися
</div>
<div class="req">
<div class="req-time">
<div class="req-time_from">13:00</div>
<span></span>
<div class="req-time_to">15:00</div>
</div>
<div class="req-restaurant">Argentina Grill</div>
<div class="req-address">Хрещатик</div>
<div class="req-name">Аліна</div>
Instagram
Приєднатися
</div>
</div>
You needed to remove the dot from the class in .classList.add('.search-active')
To add to the parent div with class = req, you can use
address.closest('div.req')
Here is an alternative version which will toggle instead of just add.
Also I use input event since it handles paste too
Lastly I use includes, textContent, trim and toLowerCase to give the user a better chance to find stuff since innerHTML could have all sorts of whitespace
If you insist on the complete value in the address field must be typed to be found, change
address.textContent.toLowerCase().trim().includes(val)
to
address.textContent === val
const search = document.querySelector('.search-form');
const addresses = document.querySelectorAll('.req-address');
search.addEventListener('input', function(e) {
const val = this.value.toLowerCase();
addresses.forEach(address => address.closest('div.req').classList.toggle('search-active', address.textContent.toLowerCase().trim().includes(val)));
});
.search-active { color: green }
<input type="text" class="search-form" />
<div class="reqs-container">
<div class="req">
<div class="req-time">
<div class="req-time_from">13:00</div>
<span></span>
<div class="req-time_to">15:00</div>
</div>
<div class="req-restaurant">Argentina Grill</div>
<div class="req-address">Оболонь</div>
<div class="req-name">Аліна</div>
Instagram
Приєднатися
</div>
<div class="req">
<div class="req-time">
<div class="req-time_from">13:00</div>
<span></span>
<div class="req-time_to">15:00</div>
</div>
<div class="req-restaurant">Argentina Grill</div>
<div class="req-address">Хрещатик</div>
<div class="req-name">Аліна</div>
Instagram
Приєднатися
</div>
</div>
This question already has answers here:
How to get the element clicked (for the whole document)?
(10 answers)
Closed 12 months ago.
When clicking on one of the tags with the same class as javascript, how to access the clicked one? I tried by clicking, I looked at the problems, but unfortunately I could not solve the problem, it is very important for me, thanks in advance. Kind regards
HTML:
<div class="money-select">
<div class="money-check">
<div class="money-check-left">
<img src="https://cdn.dsmcdn.com/ty100/product/media/images/20210408/17/78753423/161972772/0/0_org_zoom.jpg">
<h2>BTC</h2>
</div>
<div class="money-check-right">
<i class="fi-xwsdxl-chevron-wide"></i>
</div>
</div>
<div class="dropdown">
<div class="money-check">
<div class="money-check-left">
<img src="https://cdn.iconscout.com/icon/free/png-256/ethereum-2296075-1912034.png">
<h2>ETH</h2>
</div>
</div>
<div class="money-check">
<div class="money-check-left">
<img src="https://cryptologos.cc/logos/thumbs/bnb.png?v=022">
<h2>BNB</h2>
</div>
</div>
<div class="money-check">
<div class="money-check-left">
<img src="https://cryptologos.cc/logos/thumbs/shiba-inu.png?v=022">
<h2>SHIBA</h2>
</div>
</div>
<div class="money-check">
<div class="money-check-left">
<img src="https://cryptologos.cc/logos/thumbs/decentraland.png?v=022">
<h2>DTC</h2>
</div>
</div>
</div>
</div>
JS:
let moneySelect = document.querySelector(".money-select");
let moneyList = moneySelect.querySelector(".money-check");
let moneyValue = moneyList.querySelector("h1");
let input = document.getElementById("htmlinamk");
for (var i = 0; i < moneyList.length; i++) {
moneyList[i].addEventListener("click", function () {
a = moneyValue.innerText;
input.value = a;
});
}
Sorry for my bad english
The event listener function receives the event object, which has a target property that would point to the div element with class money-check. You could then traverse the DOM tree and get down to child of child and extract the inner text from the header tag. Something like this:
moneyList[i].addEventListener("click", (event) => {
const innerText = event.target.child<traverse here>.innerText;
input.value = innerText;
});
There are 2 ways to get the element that was clicked. this, or event.target. Either of the techniques will work for this example:
moneyList[i].addEventListener("click", function (e) {
let a = this.querySelector('H2').innerText;
// let a = e.target.querySelector('H2').innerText;
input.value = a;
});
I'm learning ShuffleJS to use it in a project, but I'm running into problems with the search functionality. When I'm trying to search for my items, I keep getting this error:
Cannot read property 'textContent' of null
I grabbed the search code from the docs, but it doesn't seem to work for me.
Here's some code of my search functionality:
HTML
<section class="search">
<div class="container">
<div class="row">
<div class="col-12">
<div class="form-group">
<input type="search" id="search" class="form-control">
</div>
</div>
</div>
</div>
</section>
<section>
<div class="container">
<div class="row" id="grid">
<div class="box green" data-groups='["green"]' data-title="blue">green</div>
<div class="box red" data-groups='["red"]' data-title="red">red</div>
<div class="box green" data-groups='["green"]' data-title="blue">green</div>
<div class="box red" data-groups='["red"]' data-title="red">red</div>
<div class="box green" data-groups='["green"]' data-title="blue">green</div>
<div class="box red" data-groups='["red"]' data-title="red">red</div>
<div class="col-md-2 my-sizer"></div>
</div>
</div>
</section>
JS
const Shuffle = window.Shuffle;
const element = $('#grid');
const sizer = $('.my-sizer');
const shuffle = new Shuffle(element, {
itemSelector: '.box',
sizer
})
$('#search').on('keyup', (e) => {
var searchText = e.target.value.toLowerCase();
shuffle.filter((element, shuffle) => {
var titleElement = element.querySelector('.box');
var titleText = titleElement.textContent.toLowerCase().trim(); // <= this is where the error is thrown
return titleText.indexOf(searchText) !== -1;
});
})
I've also attempted to copy and paste their example JS file here, but I get the same error mentioned above.
I've also reproduced the code written above in a CodePen!
Would anyone know where the problem is? Thanks for the help!
In your filter function, it seems element is already a div with the class box. So there's no need to look within element for an element with class box, as you've already got it.
So you can replace
var titleElement = element.querySelector('.box');
var titleText = titleElement.textContent.toLowerCase().trim(); // <= this is where the error is thrown
with
var titleText = element.textContent.toLowerCase().trim();
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I am new in javascript and I am trying to change the opacity of a div and I don't know how to do it, and I didn't find anything online.
here is my code so far:
Javascript
function close_images(){
document.getElementsByClassName("modificar_imagen").style.opacity="0";
}
HTML
<div class="modificar_imagen">
<div class="close1" onclick="close_images()"><img src="img/icons/close.png" alt="close"></div>
<div class="contenido">
<div class="grid">
<div class="image_user"><img src="img/user1.jpg"></div>
<div class="image_user"><img src="img/user1.jpg"></div>
</div>
</div>
</div>
document.getElementsByClassName("modificar_imagen") retrieves a HTMLCollection. It would be better to use document.querySelectorAll() so that you can use the forEach() method to iterate over the image collection:
document.querySelectorAll(".modificar_imagen").forEach(el=>el.style.opacity="0");
That should do it.
function close_images(){
document.querySelectorAll(".modificar_imagen").forEach(el=>el.style.opacity="0");
}
close_images()
<div class="modificar_imagen">
<div class="close1" onclick="close_images()"><img src="img/icons/close.png" alt="close"></div>
<div class="contenido">
<div class="grid">
<div class="image_user"><img src="img/user1.jpg"></div>
<div class="image_user"><img src="img/user1.jpg"></div>
</div>
</div>
</div>
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 years ago.
DOM-structure in .html
Theres .js and bootstr containers for making stylish gallery.
<script src="main.js"></script>
<div class="container-fluid" id="gal">
<div class="row">
<div class="col-md-offset-2 col-md-8 col-sm-offset-1 col-sm-10 col-xs-12">
<div class="container-fluid galbody" id="gallery3">
<h2 id="galhead">Gallery</h2>
<div id="col1">
</div>
<div id="col2">
</div>
<div id="col3">
</div>
</div>
<div class="container-fluid galbody" id="gallery2">
<div id="col1">
</div>
<div id="col2">
</div>
</div>
<div class="container-fluid galbody" id="gallery1">
<div id="col1">
</div>
</div>
</div>
</div>
</div>
Im trying to insert within .js functions and methods images that are in array arr[] urls.
there is an main.js code:
document.write("hey!");
//definin' width of browser workspace
var galdiv3 = document.getElementById("gallery3").className = "none";
var galdiv2 = document.getElementById("gallery2").className = "none";
var galdiv1 = document.getElementById("gallery1").className = "none";
//creating array of future gallerydir images paths list
var arr = [];
//creating async flow for read json with paths. after calling back func for parse read text as array list in array (arr)
fs.readFile("gallist.json", function cb(err,rd){
var imgList = JSON.parse(rd);
imgList.forEach(function(file) {
arr += file + ", ";
}, this);
console.log(arr);
});
function singleGrid()
{
galdiv1.removeAttribute(className = " none");
function imgFill(){
for (var file in arr){
var x = document.createElement("div");
x.className();
}
}
imgFill();
}
singleGrid();
Problem is there :
var galdiv3 = document.getElementById("gallery3")**.className = "none"**;
var galdiv2 = document.getElementById("gallery2")**.className = "none"**;
var galdiv1 = document.getElementById("gallery1")**.className = "none"**;
Console throws err "Uncaught TypeError: Cannot set property 'className' of null"
you're trying to access DOM element before they've been inserted into the page.
so in the expression
var galdiv3 = document.getElementById("gallery3").className = "none";
the expression document.getElementById("gallery3") returns null. as consequence: null.className throws the error.
this happens because the <script></script> tag executes his content in the moment it's added to the page, that is, during the loading of the page, before the other tags are added. For this, when the script is executed, there are no other elements in the page so that you cannot find them.
move the <script src="main.js"></script> to the bottom or simply put all the code inside the window.onload event.