简体   繁体   English

如何使用JavaScript获取列表项中的第一个和最后一个元素

[英]How to get first and last element in list item using javascript

<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: 当我单击任何按钮(项目5除外)时,它会给我一个带有下一个id元素的警报,这是我正常的操作,当我单击按钮项目5给我另一个警报时,我试图这样做,但是每次控制台都给我这条信息:

Uncaught TypeError: Cannot read property 'id' of null  

Get the Id of the element if only it exists! 如果该元素存在,则获取它的ID! I've added the if condition for that. 我为此添加了if条件。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM