Click here to Skip to main content
15,882,464 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
$(".drum")[1].click(function() { 
       let nextSibling = this.innerHTML;
     console.log(nextSibling);
     
});


I can't console.log the button using this.innerHTML

What I have tried:

$(".drum")[1].click(function() { 
       let nextSibling = this.innerHTML;
     console.log(nextSibling);
     
}); 
Posted
Updated 23-Jan-23 0:24am
v2
Comments
Member 15627495 21-Jan-23 4:38am    
while debuging :
you can do :
 console.log(this) ; 
console.table(this) ; // for arrays 

In JavaScript, you can use a for loop to target an element from an array. Here is an example:

let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === 3) {
    console.log("Found element: " + arr[i]);
    break;
  }
}


You can also use the forEach method to target an element from an array, example:

let arr = [1, 2, 3, 4, 5];
arr.forEach(function(element) {
  if (element === 3) {
    console.log("Found element: " + element);
  }
});


or you can use the find method -

let arr = [1, 2, 3, 4, 5];
let result = arr.find(element => element === 3);
console.log(result);


In these examples, the loop iterates over each element of the array, and if the element is equal to 3, the loop will print "Found element: 3" and exit.
 
Share this answer
 
Quote:
JavaScript
$(".drum")[1]
That returns the underlying HTML element, not a jQuery element wrapper.

You cannot attach an event handler to an HTML element like that. You need to use either:
JavaScript
$(".drum")[1].onclick = function(){
    console.log(this, this.innerHTML);
};
or:
JavaScript
$(".drum")[1].addEventListener("click", function(){
    console.log(this, this.innerHTML);
});
Element: click event - Web APIs | MDN[^]

Alternatively, if you want to stick with the jQuery approach, use eq instead of the indexer:
JavaScript
$(".drum").eq(1).click(function(){
    console.log(this, this.innerHTML);
});
.eq() | jQuery API Documentation[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900