Reputation: 27
I'm trying to get the innerHTML of an element but it returns undefined.
let body = e.target.previousElementSibling.innerHTML;
console.log(body);
//returns undefined
However, when I do this:
let body = e.target.previousElementSibling;
and console log it,
it returns me the element, which is:
<p class="card-text"> is the greatest </p>
so why is the innerHTML returning undefined?
Here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Microposts</title>
<body>
<div id="posts">
<div class="card-body 4" data-id="4">
<h4 class="card-title"> code </h4>
<p class="card-text"> why is this </p>
<i class="fa fa-pencil 4"> </i>
<i class="fa fa-remove 4 " style="margin-left:30px"> </i>
</div>
<div class="card-body 5" data-id="5">
<h4 class="card-title"> messi </h4>
<p class="card-text"> is the greatest </p>
<i class="fa fa-pencil 5"> </i>
<i class="fa fa-remove 5 " style="margin-left:30px"> </i>
</div>
<div class="card-body 6" data-id="6">
<h4 class="card-title"> Why is the compiler showing following code as incorrect syntax? </h4>
<p class="card-text"> I dont know </p>
<i class="fa fa-pencil 5"> </i>
<i class="fa fa-remove 5 " style="margin-left:30px"> </i>
</div>
</div>
</body>
</html>
Here's the JS Code
document.querySelector("#posts").addEventListener("click", postUpdate);
function postUpdate(e) {
if (e.target.classList.contains("fa-pencil")) {
let id = e.target.parentElement.dataset.id;
let element = e.target.parentElement;
let body = e.target.previousElementSibling.innerHTML;
let title = body.previousElementSibling.innerHTML;
console.log(body);
}
}
Upvotes: 1
Views: 367
Reputation: 27
Instead of:
let body = e.target.previousElementSibling.innerHTML;
let title = body.previousElementSibling.innerHTML;
Do:
let body = e.target.previousElementSibling.innerHTML;
let title =e.target.previousElementSibling.previousElementSibling.innerHTML;
Upvotes: 1