简体   繁体   English

将 $(element) 转换为 vanilla JS

[英]Convert $(element) to vanilla JS

I am trying to basically flash the element every time some one adds and item to their shopping cart.每当有人将商品添加到他们的购物车时,我基本上都会尝试刷新该元素。

below is a snippet from the function下面是函数的一个片段

 const elements = document.getElementsByClassName('foo-bar')

    for (const element of elements) {
      flashBackground($(element), '#bbbbbb');
    }

so I grab the dom elements, then i loop through them and flash their background, which works, but I am trying to refactor out all the old JQuery code to ES6所以我获取 dom 元素,然后我循环遍历它们并闪烁它们的背景,这可行,但我试图将所有旧的 JQuery 代码重构为 ES6

so when i console log $(element) i get back the below object所以当我控制台记录$(element)我得到下面的对象

init [a.foo-bar, context: a.foo-bar]

How do i get the equivalent of $(element) in vanilla JS?我如何在 vanilla JS 中获得相当于 $(element) 的值?

Just remove the $() like this:只需像这样删除$()

const elements = document.getElementsByClassName('foo-bar');

for (const element of elements) {
  flashBackground(element, '#bbbbbb');
}

Check and run the following Code Snippet for a pratical example of the above approach:检查并运行以下代码片段以获得上述方法的实际示例:

 const elements = document.getElementsByClassName('foo-bar'); for (const element of elements) { alert(element.innerHTML); }
 <div class="foo-bar">A</div> <div class="foo-bar">B</div> <div class="foo-bar">C</div> <div class="foo-bar">D</div>


Or you can use the querySelectorAll() method along-with the forEach() method too like this:或者你也可以像这样使用querySelectorAll()方法和forEach()方法:

const elements = document.querySelectorAll('.foo-bar');

elements.forEach(element => flashBackground(element, '#bbbbbb');)

Check and run the following Code Snippet for a pratical example of the above approach:检查并运行以下代码片段以获得上述方法的实际示例:

 const elements = document.querySelectorAll('.foo-bar'); elements.forEach(element => alert(element.innerHTML));
 <div class="foo-bar">A</div> <div class="foo-bar">B</div> <div class="foo-bar">C</div> <div class="foo-bar">D</div>

Mystery Solved.谜团已揭开。

I was making a reference to .css on a non jquery object which broke the function element.css("background");我在一个非 jquery 对象上引用了 .css,它破坏了函数element.css("background");

function flashBackground(element, color) {
...SOME CODE HERE

//needed to be
getComputedStyle(element)["background"]

jQuery's $(query) selector is effectively an abstraction of Document.querySelector() . jQuery 的$(query)选择器实际上是Document.querySelector()的抽象。 Like the jQuery implemention, querySelector() can be used to target nodes via any standard CSS selector.与 jQuery 实现一样,querySelector() 可用于通过任何标准 CSS 选择器定位节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM