How do I change the span
content when a div
block is clicked using JavaScript?
var tiles = document.querySelector(".block2");
tiles.addEventListener("click", function() {
document.getElementsByClassName(".txt").innerHTML = "Hello";
});
<div ><span >1</span></div>
<div ><span >2</span></div>
<div ><span >3</span></div>
CodePudding user response:
You need to
- get all blocks
- loop them
- add a click to each
- get the inner spans of the current block
- loop them
- change the
innerText
var tiles = document.querySelectorAll(".block1, .block2, .block3");
for (let tile of tiles) tile.addEventListener("click", function() {
for (let span of tile.querySelectorAll(".txt")) span.innerHTML = "Hello";
});
<div ><span >1</span></div>
<div ><span >2</span></div>
<div ><span >3</span></div>
CodePudding user response:
if you want to change all span innerText then,
let spans = document.getElementsByClassName("txt");
spans.forEach(element => {
element.innerText = "Hello";
});
CodePudding user response:
If you want apply the same logic to all items, set same class to all:
<div ><span >1</span></div>
<div ><span >2</span></div>
<div ><span >3</span></div>
Then addEventListener to each block:
var items = document.getElementsByClassName("block");
for (var i = 0; i < items.length; i ) {
var item = items[i];
item.addEventListener("click", function() {
var span = this.getElementsByClassName("txt")[0];
span.innerHTML = "Hello";
});
}
Inside the function, "this" is the block clicked.
CodePudding user response:
- Get all
div
that contains a class "block" usingquerySelectorAll
andwildcard
- Iterate on each
div
element and addclick
listener with a callback function - Once a div was clicked, get its first child using
firstChild
and replace its content usinginnerHTML
const blocks = document.querySelectorAll("[class*='block']");
blocks.forEach(e => {
e.addEventListener("click", () => {
e.firstChild.innerHTML = "Hello";
});
})
<div ><span >1</span></div>
<div ><span >2</span></div>
<div ><span >3</span></div>
CodePudding user response:
You need to fetch all divs. You can use for example this selector: document.querySelectorAll('[class^="block"]');
Then you can assign ervery div a click event.
const divs = document.querySelectorAll('[class^="block"]');
divs.forEach(d => {
d.addEventListener("click", () => {
d.firstChild.innerHTML = "Hello";
});
})
div {
height: 20px;
background: gray;
padding: 5px;
margin: 5px;
width: 300px;
}
<div ><span >1</span></div>
<div ><span >2</span></div>
<div ><span >3</span></div>