原文: 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的更多相关文章

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

  2. 深入理解JavaScript系列(1):编写高质量JavaScript代码的基本要点

    深入理解JavaScript系列(1):编写高质量JavaScript代码的基本要点 2011-12-28 23:00 by 汤姆大叔, 139489 阅读, 119 评论, 收藏, 编辑 才华横溢的 ...

  3. JavaScript高级程序设计(二):在HTML中使用JavaScript

    一.使用<script>元素 1.<script>元素定义了6个属性: async:可选.表示应该立即下载脚本,但不应该妨碍页面中的其他操作,比如下载其他资源或等待加载其他脚本 ...

  4. JavaScript学习总结(四)——this、原型链、javascript面向对象

    一.this 在JavaScript中this表示:谁调用当前函数this就指向谁,不知道调用者时this指向window. JavaScript是由对象组成的,一切皆为对象,万物皆为对象.this是 ...

  5. JS事件 什么是事件?JavaScript 创建动态页面。事件是可以被 JavaScript 侦测到的行为。 网页中的每个元素都可以产生某些可以触发 JavaScript 函数或程序的事件。

    什么是事件 JavaScript 创建动态页面.事件是可以被 JavaScript 侦测到的行为. 网页中的每个元素都可以产生某些可以触发 JavaScript 函数或程序的事件. 比如说,当用户单击 ...

  6. 《JavaScript高级程序设计》——第二章在HTML使用JavaScript

    这章讲的是JavaScript在HTML中的使用,也就是<script>元素的属性.书中详细讲了async.defer.src和type四个<script>的属性. 下面是对第 ...

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

  8. [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 - ...

  9. Deleting array elements in JavaScript - delete vs splice

    javascript 数组中删除元素用 array.splice(start, deleteCount);这个方法. ----------------------------------------- ...

随机推荐

  1. require.js使用baseUrl + paths导入文件配置的3种方法

    //main.js requirejs.config({ baseUrl: 'lib/js',//参照于引入这个js文件的index.html页面的相对路径,因为此时mian.js文件已经导入到了in ...

  2. css深入理解之border

    1.  border-width border-width不支持百分比,类似的还有outline,box-shadow,text-shadow等 border-width支持关键字:thin(1px, ...

  3. mysql table status

    SHOW TABLE STATUS 能获得表的信息 可以SHOW TABLE STATUS where name='表名'

  4. 进程注入后门工具Cymothoa

    进程注入后门工具Cymothoa   Cymothoa是一款隐秘的后门工具.它通过向目标主机活跃的进程注入恶意代码,从而获取和原进程相同的权限.该工具最大的优点就是不创建新的进程,不容易被发现.由于该 ...

  5. 【原创】项目管理软件之争,禅道和JIRA大对比

    本文摘要: 一. 产品介绍 二. 界面设计 1. 界面颜色设计 2. 布局结构 三. 功能区别 四. 价格对比 五. 后期服务 六. 优缺点 七. 总结 说到项目管理软件,不得不提的是禅道和JIRA. ...

  6. Scrum实施调查案例

    什么是敏捷开发方法?什么是SCRUM? 有人在这个字面上下功夫,说敏捷就是反应要灵敏,动作要快捷:有人还在字面上进行延伸,说敏捷就是又好又快,或者就是多快好省:有人说敏捷就是光写代码不写文档:有人觉得 ...

  7. [PKUSC2018]最大前缀和(DP)

    题意:求一个序列随机打乱后最大前缀和的期望. 考场上发现不管怎么设状态都写不出来,实际上只要稍微转换一下就好了. 一个前缀[1..k]是最大前缀,当且仅当前面的所有后缀[k-1,k],[k-2,k], ...

  8. bzoj DZY Loves Math V

    Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 509  Solved: 284[Submit][Status][Discuss] Descriptio ...

  9. 【树状数组】Gym - 101147J - Whistle's New Car

    题意就是对每个点i,统计在其子树内(不含自身),且depj-depi<=xj的点有多少个. 把点分别按照dep-x和dep进行排序,离线处理, 每次把dep-x小于等于当前dep值的点插入树状数 ...

  10. [HDU6252]Subway Chasing

    题目大意: 一条直线上有n个点,两个人在直线上走,保持x的距离. 告诉你m条信息,告诉你一个人在ab之间时,另一个人在cd之间. 问这些信息是否矛盾,如果不矛盾,求相邻两点之间的最小距离. 思路: m ...