Reputation: 45
<script>
function editMediaInfo(mediaID){
var nex = document.getElementById(mediaID).nextElementSibling.nextElementSibling.id;
alert(nex);
console.log(nex);
}
</script>
<?php
$x = 1;
echo "<ul>";
while($x <= 5)
{
echo "<li id={$x}> item {$x} </li>";
?>
<button onclick="editMediaInfo('<?php echo $x; ?>')">Click</button>
<?php
$x++;
}
echo "</ul>";
?>
When I click any button (except item 5) it gives me an alert with next id element and this normal what I need here to do that when I click button item 5 give me another alert I tried to do this but every time console give me this message:
Uncaught TypeError: Cannot read property 'id' of null
Upvotes: 1
Views: 147
Reputation: 2613
Get the Id of the element if only it exists! I've added the if condition for that.
function editMediaInfo(mediaID){
var nex = document.getElementById(mediaID).nextElementSibling.nextElementSibling;
var nextId="";
if(nex!=null){
nextId=nex.id;
alert(nextId);
}
else{
alert("no next element");
}
console.log(nextId);
}
Upvotes: 1