javascript选择器_如何通过选择正确JavaScript选择器来避免沮丧

javascript选择器

选择器如何影响代码的快速指南 (A quick guide on how selectors affect your code)

While working on a project, I ran into an issue in my code. I was attempting to define multiple HTML elements into a collection and then change those elements based on some preset conditions. I struggled for roughly four hours of coding time (across two days) debugging my code and trying to figure out why I wasn’t getting my desired outcome.

在处理项目时,我的代码遇到了一个问题。 我试图将多个HTML元素定义到一个集合中,然后根据一些预设条件更改这些元素。 我花了大约四个小时的时间(大约两天)来调试我的代码,并试图弄清为什么没有得到理想的结果,这让我很费力。

Turns out I had used document.querySelectorAll() to assign my elements to a variable, and then I was attempting to change those elements. The only problem is that particular JavaScript selector returns a static node list. Since it isn’t a live representation of the elements, I wasn’t able to change them later in my code.

原来,我曾使用document.querySelectorAll()将元素分配给变量,然后尝试更改这些元素。 唯一的问题是特定JavaScript选择器返回静态节点列表 。 由于它不是元素的实时表示,因此以后我无法在代码中对其进行更改。

假设条件 (Assumptions)

In this article, I assume a few things to be true:

在本文中,我假设有几件事情是正确的:

  • You are working in “plain or vanilla” JavaScript (no framework / library)

    您正在使用“普通的或原始的” JavaScript(没有框架/库)
  • You have a basic understanding of JavaScript elements / selectors

    您对JavaScript元素/选择器有基本的了解
  • You have a basic understanding of the DOM

    您对DOM有基本的了解

坚韧不拔 (The Nitty-gritty)

In the event I have assumed too much, I have provided links to relevant material within the article that I hope will be helpful.

如果我承担过多,我提供了文章中相关材料的链接,希望对您有所帮助。

JavaScript is such a vast and rich ecosystem that it’s no surprise that there are many ways of accomplishing the same task. Depending on your task, the way it is accomplished matters to a certain degree.

JavaScript是一个如此庞大而丰富的生态系统,以多种方式完成同一任务也就不足为奇了。 根据您的任务,完成的方式在一定程度上很重要。

You can dig a hole with your hands, but it’s much easier and more efficient to do it with a shovel.

您可以用手挖一个洞,但是用铲子挖起来要容易得多,效率也更高。

To that end, I hope to “hand you a shovel” after you’ve read this article.

为此,我希望在阅读本文后为您“铲”。

为工作选择合适的工具 (Choosing the right tool for the job)

I’ve had the question, “Which element selector should I use?” several times. Until now, I haven’t had much desire or need to learn the difference as long as my code produced the desired result. After all, what does the color of the taxi matter as long as it gets you to your destination safely and in a timely manner…right?

我有一个问题,“我应该使用哪个元素选择器?” 几次。 到目前为止,只要我的代码产生了期望的结果,我就没有太多的愿望或需要学习区别。 毕竟,只要它能安全,及时地到达目的地,出租车的颜色有什么关系?对吗?

Let’s start with some of the ways to select DOM elements in JavaScript. There are more ways (I believe) to select elements, but the ones listed here are by far the most prevalent I’ve come across.

让我们从在JavaScript中选择DOM元素的一些方法开始。 (我相信)有更多选择元素的方法,但是到目前为止,这里列出的方法是我遇到的最普遍的方法。

document.getElementById() (document.getElementById())

These will only ever return one (1) element because, by their nature, ID’s are unique and there can only be one (with the same name) on the page at a time.

它们只会返回一(1)个元素,因为从本质上讲,ID是唯一的,并且一次在页面上只能有一个(同名)。

It returns an object that matches the string passed into it. It returns null if no matching ID is found in your HTML.

它返回与传递给它的字符串匹配的对象。 如果在HTML中找不到匹配的ID,则返回null

Syntax example -> document.getElementById(‘main_content’)

语法示例-&g t; document.getElementById('main_conten t')

Unlike some selectors that we’ll get to later in the article, there is no need for a # to denote element id.

与我们将在本文后面介绍的一些选择器不同,不需要使用#来表示元素ID。

document.getElementsByTagName() (document.getElementsByTagName())

Notice the “S” in elements — this selector returns multiples in an array-like structure known as an HTML collection — all of the document is searched including the root node (the document object) for a matching name. This element selector starts at the top of the document and continues down, searching for tags that match the passed-in string.

注意元素中的“ S”-此选择器返回倍数 阵列状结构 称为HTML集合 -搜索所有文档,包括根节点 (文档对象)以找到匹配的名称。 此元素选择器从文档顶部开始,一直向下,搜索与传入字符串匹配的标签。

If you are looking to use native array methods you’re out of luck. That is, unless you convert the returned results into an array to iterate over them, or use the ES6 spread operator — both of which are beyond the scope of this article. But I wanted you to know it is possible to use array methods if you wish to.

如果您希望使用本机数组方法,那么您会很不幸。 也就是说,除非您将返回的结果转换为数组以对其进行迭代,或者使用ES6 传播运算符 -二者均不在本文的讨论范围之内。 但是我想让您知道是否可以使用数组方法。

Syntax example -> document.getElementsByTagName(‘header_links’). This selector also accepts p, div, body, or any other valid HTML tag.

语法示例-&g t; document.getElementsByTagName('header_li nks')。 此选择器还接受p,div,body或任何其他有效HTML标记。

document.getElementsByClassName() (document.getElementsByClassName())

Class name selector — again notice the “S” in elements — this selector returns multiples in an array-like structure known as an HTML collection of class names. It matches the passed-in string (can take multiple class names, although they are separated by a space), searches all of the document, can be called on any element, and only returns descendants of the passed in class.

类名选择器-再次注意元素中的“ S”-此选择器返回倍数 阵列状结构 被称为类名称的HTML集合 。 它与传入的字符串匹配(可以用多个类名,尽管它们之间用空格隔开),搜索所有文档,可以在任何元素上调用,并且仅返回传入类的后代。

Also, no . (period) is needed to denote class name

另外,没有。 需要(句号)来表示班级名称

Syntax example: document.getElementsByClassName(‘className’)

语法示例: document.getElementsByClassName('classNam e')

document.querySelector() (document.querySelector())

This selector will only ever return one (1) element.

此选择器将仅返回一(1)个元素。

Only the first element matching the passed-in string will be returned. If no matches for the provided string are found, null is returned.

仅返回与传入字符串匹配的第一个元素。 如果找不到与提供的字符串匹配的字符串,则为null 返回。

Syntax example: document.querySelector(‘#side_note’) or document.querySelector(‘.header_links’)

语法示例: document.querySelector('#side_note ') 或document.querySelector('。header_link s')

Unlike all of our previous examples, this selector requires a . (period) to denote class or an # (octothorp) to denote an ID and works with all CSS selectors.

与我们之前的所有示例不同,此选择器需要一个。 (句号)表示类,或 (octothorp)表示ID,并与所有CSS选择器一起使用。

document.querySelectorAll() (document.querySelectorAll())

This selector returns multiples that match the passed-in string and arranges them into another array like structure known as a node list.

该选择器返回与传入的字符串匹配的倍数 ,并将它们排列到另一个数组中,如结构称为节点列表

As with some of the previous examples, the node list cannot make use of native array methods like .forEach(). So if you want to use those, you must first convert the node list into an array. If you do not wish to convert, you can still iterate over the node list with a for…in statement.

与前面的一些示例一样,节点列表不能使用诸如.forEach( )之类的本机数组方法 。 因此,如果要使用它们,则必须首先将节点列表转换为数组。 如果您不希望进行转换,则仍然可以使用af 或…in语句遍历节点列表。

The passed in string must match a valid CSS selector — id, class names, types, attributes, values of attributes, etc.

传入的字符串必须与有效CSS选择器匹配-ID,类名,类型,属性,属性值等。

Syntax example: document.querySelectorAll(‘.footer_links’)

语法示例: document.querySelectorAll('。footer_link s')

结语 (Wrapping up)

By choosing the right selector for your coding needs, you’ll avoid many of the pitfalls I’ve fallen into. It can be incredibly frustrating when your code doesn’t work, but by ensuring that your selector matches your situational needs, you’ll have no trouble “digging with your shovel” :)

通过选择适合您的编码需求的选择器,可以避免我遇到的许多陷阱。 当您的代码不起作用时,它可能会令人难以置信的令人沮丧,但是通过确保您的选择器满足您的情况需求,您将“用铲子挖矿”毫无问题:)

Thank you for reading through this post. If you enjoyed it, please consider donating some claps to help others find it as well. I publish (actively managing my schedule to write more) related content on my blog. I’m also active on Twitter and am always happy to connect with other developers!

感谢您阅读这篇文章。 如果您喜欢它,请考虑捐赠一些拍手以帮助其他人找到它。 我在博客上发布(积极管理我的日程安排以写更多)相关内容。 我也在Twitter上很活跃,很高兴与其他开发人员联系!

翻译自: https://www.freecodecamp.org/news/how-to-avoid-frustration-by-choosing-the-right-javascript-selector-73c64c3906b6/

javascript选择器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值