【问题标题】:How to fetch lastChild, firstChild and nextSibling content in JavaScript?如何在 JavaScript 中获取 lastChild、firstChild 和 nextSibling 内容?
【发布时间】:2014-04-13 08:48:18
【问题描述】:

我想知道如何在 JavaScript 中获取 lastChild、firstChild 和 nextSibling 内容。
这是我的示例代码:

<div id="main">
    <div id="first">content 1</div>
    <div id="second">content 2</div>
    <div id="third">content 3</div>
</div>
<script>
alert (document.getElementById('main').firstChild.nodeValue);
alert (document.getElementById('main').lastChild.nodeValue);
alert (document.getElementById('first').nextSibling.nodeValue);
</script>

我尝试了这段代码,但它们不起作用……只打开一个空警报!

【问题讨论】:

    标签: javascript css-selectors nextsibling


    【解决方案1】:

    也许你想要firstElementChildnextElementSiblinglastElementChild
    那么

    alert (document.getElementById('main').firstElementChild.innerHTML);
    alert (document.getElementById('main').lastElementChild.innerHTML);
    alert (document.getElementById('first').nextElementSibling.innerHTML);
    

    请解释清楚,您所说的“确切”是什么意思?

    你可以编辑它:

    document.getElementById('main').firstElementChild.innerHTML="some text";
    

    你可以存储它:

    var fec=document.getElementById('main').firstElementChild.innerHTML;
    

    你可以删除它:

    document.getElementById('main').removeChild(document.getElementById('main').firstElementChild);
    

    你可以替换里面的文字:

    document.getElementById('main').firstElementChild.innerHTML=document.getElementById('main').firstElementChild.innerHTML.replace(/new_text/g,"text_to_replace")
    

    你可以把它拆分成一个字符数组:

    var array=document.getElementById('main').firstElementChild.innerHTML.split("");
    

    您可以在其中添加一些文本:

    document.getElementById('main').firstElementChild.appendChild("some text");
    

    【讨论】:

    • 不幸的是没有。它返回undefined
    • @MohammadBagherSaberi 已编辑
    • @MohammadBagherSaberi 怎么样? document.getElementById('main').firstElementChild - 完全使用它
    猜你喜欢
    • 2011-10-27
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 2015-02-19
    • 2021-08-22
    • 2010-12-05
    • 2021-04-13
    • 2017-05-22
    相关资源
    最近更新 更多