After pressing the button, obtain the first child element of the element and the contents of the element (e.g.a)I would like to see in a dialog, but it says undefined.How do I fix this?
<!DOCTYPE html>
<html lang="ja">
<head>
<metacharset="utf-8">
<title> Ayeo Shop </title>
<link href="css/bootstrap.min.css"rel="stylesheet">
<link type="text/css"rel="stylesheet" href="css/bootstrap-timepicker.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<body>
<divid="childcatch">
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
<span>e>/span>
</div>
<script type="text/javascript">
function findElement(){
variable= document.getElementById("childcatch");
varchild = element.firstChild;
alert(child.innerHTML);
}
</script>
<button onclick="findElement()">Get First Child</button>
</body>
</html>
In conclusion, firstElementChild
instead of firstChild
will solve the problem.
firstChild
returns a node, not limited to Element, with a new line and a blank space between <divid="childcatch">
and <span>a</span>
, where text node is created.And the text node does not have the innerHTML
property, so undefined
returned.
html5, so another approach is to use documentSode(a) with tag. Get the first child element of the element is represented by the CSS selector as can be written as (DOM is intended for Node, so #childcatch>*:first-child
, sofunction findElement(){
varchild= document.querySelector("#childcatch>*:first-child");
alert(child.innerHTML);
}
firstChild
does not mean it, but :first-child
is acceptable because CSS Selector is primarily intended for Element).
© 2024 OneMinuteCode. All rights reserved.