These firstChild
and lastChild
both are HTML element properties in Javascript.
In Html documentation, the first child element must be written just after its parent element without breaking the line (or without pressing the 'enter'). Otherwise, you will see an empty result as the first child element's value.
We use firstChild property when we want to know the first element in a parent element. After that, we can easily get its data by using another property innerHTML
or textContent
.
Example-
<!DOCTYPE html>
<html>
<head>
<title>firstChild & lastChild - jaischool.com</title>
</head>
<body>
<p id="para"><span>jaischool</span><br />
<span>jai</span><br />
<span>school</span></p><br />
<script>
var result=document.getElementById("result");
var paragra=document.getElementById("para").firstChild.innerHTML;
alert(paragra);
</script>
</body>
</html>
If you want to get the only element first-element then do not use textContent property.
Opposite this, lastChild property is to examine the last child element in a parent element in an Html document.
Example-
<!DOCTYPE html>
<html>
<head>
<title>firstChild & lastChild - jaischool.com</title>
</head>
<body>
<p id="para"><span>jaischool</span><br />
<span>jai</span><br />
<span>school</span></p><br />
<script>
var result=document.getElementById("result");
var paragra=document.getElementById("para").lastChild.innerHTML;
alert(paragra);
</script>
</body>
</html>
Publish A Comment