0

Objective

Get the url of each image and add that as a background to it's parent article, in a vuejs project

Question

How should I refactor the code originally written in jQuery?


JS - original from other author

$(".polaroid").wrap("<div class='polaroid-frame'><div class='polaroid-image'>");
$(".polaroid").each(function() {
  var $this = $(this);
  var imgLink = $this.attr("src");
  var bg = "url("+imgLink+")";

  $this.closest(".polaroid-image").css({
    "background-image": bg
  });
});

JS - refactored for my project

$(".polaroid article img").each(function() {
  var $this = $(this);
  var imgLink = $this.attr("src");
  var bg = "url("+imgLink+")";

  $this.closest("article").css({
    "background-image": bg
  });
});

My demo on codepen


Background

I am taking code from another project but it was written in jQuery. I don't want to use jQuery, instead i just need to write this in ES6, or just plain javascript.

I so far found one related question, Finding closest element without jQuery , but it was too different to be able to make much use of it.

I looked at the mozilla documentation https://developer.mozilla.org/en-US/docs/Web/API/Element/closest , which leads me to think my code should translate to

el.closest("article");

but then how would I wrap that in a way that would pass the CSS values. I looked up documentation from w3 https://www.w3schools.com/js/js_htmldom_css.asp and found this example

document.getElementById("p2").style.color = "blue";

So I think I should do

document.[unclear what to do here].style.background-image = /* what goes here for the variable? */;
Community
  • 1
  • 1
JGallardo
  • 11,074
  • 10
  • 82
  • 96

1 Answers1

2

From your refactored JS, to translate it into plain JS, you need to

(1) Iterate over the selected elements (can be done easily with querySelectorAll)

(2) Get the element's src attribute

(3) Set the closest article's background-image to that src

So, it should be pretty simple:

document.querySelectorAll('.polaroid article img').forEach((img) => {
  const { src } = img;
  img.closest('article').style.backgroundImage = `url(${src})`;
});

Note that when setting style properties directly, sometimes the CSS string you'd want to use (eg. background-image) wouldn't be valid syntax in Javascript. In these cases, generally turn the words-separated-by-dashes into camelCase. (backgroundImage)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320