JavaScript basics: 2 ways to get child elements with JavaScript
原文: https://blog.mrfrontend.org/2017/10/2-ways-get-child-elements-javascript/
Along the lines of other frameworks such as jQuery or Prototype, shortening the "querySelector" name can be convenient:
function $ (selector, el) {
if (!el) {el = document;}
return el.querySelector(selector);
}
function $$ (selector, el) {
if (!el) {el = document;}
return el.querySelectorAll(selector);
// Note: the returned object is a NodeList.
// If you'd like to convert it to a Array for convenience, use this instead:
// return Array.prototype.slice.call(el.querySelectorAll(selector));
}
alert($('#myID').id);

--------------------------------------------------------------------------------
In jQuery, it is super easy to get the child elements of a parent HTML element. But do you know how it works with Vanilla JavaScript?
Today I want to show you 2 ways how you can use Vanilla JavaScript to get the child elements, even when you don’t know what’s in the parent element.
If you like reading instead of watching a video? Please scroll down to continue reading.
Looking for the video resources? Scroll to the bottom!
Let’s start with a simple webshop page.
HTML
<header class="product__list-header">
<h2>Webshop</h2>
</header>
<section class="product__list">
<div class="product__item">
<img src="http://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
<div class="product__item fun__class">
<img src="https://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
<div class="product__item">
<img src="https://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
<div class="product__item">
<img src="https://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
<div class="product__item">
<img src="https://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
</section>
As you noticed, I used BEM as naming convention for my webshop example page.
#1 element.children
The first way to get the child elements is with the element.children. If you want to check out what kind of properties the DOM Element Object has for you, check it on W3schools. That is btw one of my favorite websites to check JavaScript example’s & documentation.
JavaScript
var productList = document.querySelector('.product__list').children;
console.log('productList: ', productList);
In the console log, you will find a.HTMLCollection Check the property__proto__, you will find out that he is not an Array.
Loop over the children
The children property will return a.HTMLCollection So you can loop over it with the plain-old For-loop.
for (i = 0; i < productList.length; i++) {
console.log('productList[i]: ', productList[i]);
}
Check my element.children jsbin example.
#2 document.querySelectorAll
If you know which elements are in a parent element, you can adjust the selector to:..product__list .product__item With this selector, you target al the product items inside the product list.
If you don’t know which elements are in the parent element, I would recommend the element.children way. Because then you will definitely get all the children back.
Maybe you remind the querySelectorAll from my previous blog post, but I don’t mind to show it again .
JavaScript
var productList = document.querySelectorAll('.product__list .product__item');
console.log('productList: ', productList);
In the console log, you will find a NodeList. If you check the __proto__ you will find out that he is not an Array.
Just like the HTMLCollection, you can use the For-loop to loop over each element in the NodeList.
for (i = 0; i < productList.length; i++) {
console.log('product: ', productList[i]);
}
Check my querySelectorAll jsbin example.
Conclusion: element.children VS querySelectorAll
But now is the question, which one do you use?
You know the child elements
In the case you know what child elements there are in the parent element, it is good to use the document.querySelectorAll method.
This a much faster way to target them with the CSS selector. And because of the, querySelectorAll it doesn’t matter how much elements there are.
You don’t know the child elements
In the case you don’t know what child elements you can expect, you need the. element.children All the elements inside the parent element will come back with the DOM Element Object.
JavaScript basics: 2 ways to get child elements with JavaScript的更多相关文章
- 3 Ways to Preload Images with CSS, JavaScript, or Ajax---reference
Preloading images is a great way to improve the user experience. When images are preloaded in the br ...
- 深入理解JavaScript系列(1):编写高质量JavaScript代码的基本要点
深入理解JavaScript系列(1):编写高质量JavaScript代码的基本要点 2011-12-28 23:00 by 汤姆大叔, 139489 阅读, 119 评论, 收藏, 编辑 才华横溢的 ...
- JavaScript高级程序设计(二):在HTML中使用JavaScript
一.使用<script>元素 1.<script>元素定义了6个属性: async:可选.表示应该立即下载脚本,但不应该妨碍页面中的其他操作,比如下载其他资源或等待加载其他脚本 ...
- JavaScript学习总结(四)——this、原型链、javascript面向对象
一.this 在JavaScript中this表示:谁调用当前函数this就指向谁,不知道调用者时this指向window. JavaScript是由对象组成的,一切皆为对象,万物皆为对象.this是 ...
- JS事件 什么是事件?JavaScript 创建动态页面。事件是可以被 JavaScript 侦测到的行为。 网页中的每个元素都可以产生某些可以触发 JavaScript 函数或程序的事件。
什么是事件 JavaScript 创建动态页面.事件是可以被 JavaScript 侦测到的行为. 网页中的每个元素都可以产生某些可以触发 JavaScript 函数或程序的事件. 比如说,当用户单击 ...
- 《JavaScript高级程序设计》——第二章在HTML使用JavaScript
这章讲的是JavaScript在HTML中的使用,也就是<script>元素的属性.书中详细讲了async.defer.src和type四个<script>的属性. 下面是对第 ...
- 7 JavaScript Basics Many Developers Aren't Using (Properly)【转】
JavaScript, at its base, is a simple language that we continue to evolve with intelligent, flexible ...
- [HTML5] Add an SVG Image to a Webpage and Get a Reference to the Internal Elements in JavaScript
We want to show an SVG avatar of the patio11bot, so we'll do that in three ways: Using an img tag - ...
- Deleting array elements in JavaScript - delete vs splice
javascript 数组中删除元素用 array.splice(start, deleteCount);这个方法. ----------------------------------------- ...
随机推荐
- 给tomcat单独配置jdk
在catalina 文件 加这句话,前面加 export JAVA_HOME=/home/apache-tomcat-8.5.8/jdk1.8.0_101
- shell里面比较大小
#!/bin/bashif [ $1 -gt $2 ]then echo "$1>$2"else echo "$2>$1"fi# 数字判断一些命令 ...
- 安装并启用rabbitmq服务器
1.确保Erlang已经安装 2.安装rabbitmq服务器 [root@bogon yum.repos.d]# rpm --import https://dl.bintray.com/rabbitm ...
- 最小生成树(Minimum Spanning Tree)——Prim算法与Kruskal算法+并查集
最小生成树——Minimum Spanning Tree,是图论中比较重要的模型,通常用于解决实际生活中的路径代价最小一类的问题.我们首先用通俗的语言解释它的定义: 对于有n个节点的有权无向连通图,寻 ...
- Codeforces #427 Div2 D
#427 Div2 D 题意 给出一个字符串,求它的子串中为 \(k-palindrome\) 的个数. \(1-palindrome\) 要求是一个回文串. \(k-palindrome (k &g ...
- 在MYSQL中插入当前时间,就象SQLSERVER的GETDATE()一样,以及对mysql中的时间日期操作。
在看sql教程的时候,我学的是mysql,但是教程上面的一点在mysql里面是不支持的,所以就找了其他的替代的办法 sql教程上面是这样的: 通过使用类似 GETDATE() 这样的函数,DEFAUL ...
- [xsy1515]小学生数学题
题意:求$\begin{align*}\left(\sum\limits_{i=1}^n\dfrac 1i\right)\%\ p^k\end{align*}$ 数学真是太可爱了== 直接推公式 设$ ...
- 【pb_ds】【平衡树启发式合并】【并查集】bzoj2733 [HNOI2012]永无乡
用并查集维护联通性.对每个联通块维护一个平衡树.合并时启发式合并.比较懒,用了pb_ds. #include<cstdio> #include<ext/pb_ds/assoc_con ...
- 【树状数组】bzoj2743 [HEOI2012]采花
http://www.cnblogs.com/proverbs/archive/2012/10/29/2745281.html (↑)这样处理之后,每次询问时,对于每种颜色,从1到其倒数第二次出现的位 ...
- 【bzoj1486】【[HNOI2009]梦幻布丁】启发式链表合并(详解)
(画师当然是武内崇啦) Description N个布丁摆成一行,进行M次操作.每次将某个颜色的布丁全部变成另一种颜色的,然后再询问当前一共有多少段颜色.例如颜色分别为1,2,2,1的四个布丁一共有3 ...