简体   繁体   中英

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

so when i console log $(element) i get back the below object

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

How do i get the equivalent of $(element) in vanilla JS?

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:

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");

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

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

jQuery's $(query) selector is effectively an abstraction of Document.querySelector() . Like the jQuery implemention, querySelector() can be used to target nodes via any standard CSS selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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