给定一个HTML文档, 任务是选择一个特定的元素, 并借助JavaScript获得父元素的所有子元素。
方法1:
- 选择要选择其子元素的元素。
- 采用.children属性以访问element的所有子级。
- 根据索引选择特定的子级。
<
!DOCTYPE HTML>
<
html>
<
head>
<
title>
Finding child element of parent with pure JavaScript.
<
/title>
<
style>
.parent {
background: green;
color: white;
}
.child {
background: blue;
color: white;
margin: 10px;
}
<
/style>
<
/head>
<
body style = "text-align:center;
">
<
h1 style = "color:green;
">
lsbin
<
/h1>
<
p id = "GFG_UP" style =
"font-size: 15px;
font-weight: bold;
">
<
/p>
<
div class = "parent" id = "parent">
Parent
<
div class = "child">
Child
<
/div>
<
/div>
<
br>
<
button onclick = "GFG_Fun()">
click here
<
/button>
<
p id = "GFG_DOWN" style =
"font-size: 24px;
font-weight: bold;
color: green;
">
<
/p>
<
script>
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
up.innerHTML = "Click on the button select the child node.";
function GFG_Fun() {
parent = document.getElementById('parent');
children = parent.children[0];
down.innerHTML = "Text of child node is - '"
+ children.innerHTML + "'";
}
<
/script>
<
/body>
<
/html>
输出如下:
在单击按钮之前:
文章图片
单击按钮后:
文章图片
方法二:
- 选择要选择其子元素的父元素。
- 采用.querySelector()方法在父母身上。
- 使用child的className选择特定的孩子。
<
!DOCTYPE HTML>
<
html>
<
head>
<
title>
How to get the child element of
a parent using JavaScript ?
<
/title>
<
style>
.parent {
background: green;
color: white;
}
.child1 {
background: blue;
color: white;
margin: 10px;
}
.child2 {
background: red;
color: white;
margin: 10px;
}
<
/style>
<
/head>
<
body style = "text-align:center;
">
<
h1 style = "color:green;
">
lsbin
<
/h1>
<
p id = "GFG_UP" style =
"font-size: 15px;
font-weight: bold;
">
<
/p>
<
div class = "parent" id = "parent">
Parent
<
div class = "child child1">
Child1
<
/div>
<
div class = "child child2">
Child2
<
/div>
<
/div>
<
br>
<
button onclick = "GFG_Fun()">
click here
<
/button>
<
p id = "GFG_DOWN" style =
"font-size: 24px;
font-weight: bold;
color: green;
">
<
/p>
<
script>
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
up.innerHTML = "Click on the button select the child node.";
function GFG_Fun() {
parent = document.getElementById('parent');
children = parent.querySelectorAll('.child');
down.innerHTML = "Text of child node is - '"
+ children[0].innerHTML + "' and '"
+ children[1].innerHTML + "'";
}
<
/script>
<
/body>
<
/html>
输出如下:
在单击按钮之前:
文章图片
【如何使用JavaScript获取父级的子级元素()】单击按钮后:
文章图片
推荐阅读
- 算法题(如何解决分数背包问题(代码实现))
- CSS基本语法和选择器用法示例
- SDE1 FTE/6M实习生的Amazon面试体验(校园内)
- 算法设计(用信号量来解决哲学家问题)
- jQuery jQuery.fx.interval属性用法示例
- JavaScript数组valueOf()方法使用示例
- PHP Ds\Map __construct()函数用法示例详解
- 亚马逊面试体验分享| SDE-1的校园内
- windows 7ghost介绍