1

I would like to know how can I fetch the lastChild, firstChild and nextSibling content in JavaScript.
This is my sample code:

<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>

I tried this code, but they did not work ... an empty alert opens only!

Mohammad Saberi
  • 12,864
  • 27
  • 75
  • 127

1 Answers1

1

Maybe you wanted firstElementChild, nextElementSibling and lastElementChild ?
Then

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

Explain clearly, please, what do you mean by using "exactly"?

You can edit it:

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

You can store it:

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

You can remove it:

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

You can replace text in it:

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

You can split it into an array of characters:

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

You can add some text to it:

document.getElementById('main').firstElementChild.appendChild("some text");
AlieN
  • 555
  • 2
  • 16