Home > Software design >  How can I apply function to all elements of a class?
How can I apply function to all elements of a class?

Time:10-14

I am a novice and I have a page that displays job offers, I want to create a function that changes the logo of a company according to the company name mentionned in first 50 characters. The function below works only for the first element of a class. How can I make it work with all the class elements independently?

function logo_switch() {
  let anonce = document.querySelector(".anonce").querySelector(".anonceText").innerHTML;
  console.log(anonce);

  let logo_A = anonce.indexOf('A');
  let logo_B = anonce.indexOf('B');
  let logo_C = anonce.indexOf('C');
  let logo_D = anonce.indexOf('D');
  let logo_E = anonce.indexOf('E');
  let logo_F = anonce.indexOf('F');
  let logo_G = anonce.indexOf('G');

  var img = document.querySelector(".anonceLogo");



  if ((logo_A > 0) && (logo_A < 50)) {
    img.setAttribute("src", "img/a.png");
  } else {
    console.log(0);
  };

  if ((logo_B > 0) && (logo_B < 50)) {
    img.setAttribute("src", "img/b.jpg");
  } else {
    console.log(0);
  };

  if ((logo_C > 0) && (logo_C < 50)) {
    img.setAttribute("src", "img/c.jpg");
  } else {
    console.log(0);
  };

  if ((logo_D > 0) && (logo_D < 50)) {
    img.setAttribute("src", "img/d.jpg");
  } else {
    console.log(0);
  };

  if ((logo_E > 0) && (logo_E < 50)) {
    img.setAttribute("src", "img/e.jpg");
  } else {
    console.log(0);
  };

  if ((logo_F > 0) && (logo_F < 50)) {
    img.setAttribute("src", "img/f.png");
  } else {
    console.log(0);
  };
  if ((logo_G > 0) && (logo_G < 50)) {
    img.setAttribute("src", "img/g.png");
  } else {
    console.log(0);
  };
};
<body onl oad="logo_switch()">
  <div >
    <h2>Job 1</h2>
    <div >
      <img >
      <p >
        A
      </p>
    </div>
  </div>
  <div >
    <h2>Job 2</h2>
    <div >
      <img >
      <p >
        B
      </p>
    </div>
  </div>
  <div >
    <h2>Job 3</h2>
    <div >
      <img >
      <p >
        C
      </p>
    </div>
  </div>
  <div >
    <h2>Job 4</h2>
    <div >
      <img >
      <p >
        D
      </p>
    </div>
  </div>
</body>

CodePudding user response:

One approach is as below, with explanatory comments in the JavaScript:

const logo_switch = () => {
  // using document.querySelectorAll() to retrieve all matching elements, along with
  // and Array-literal and the spread operator to convert the iterable NodeList into
  // an Array to provide access to Array methods:
  let anonceTextElements = [...document.querySelectorAll(".anonceText")];

  // the letters (or company names) you're looking for:
  const logoLetters = ['A', 'B', 'c', 'D', 'E', 'F', 'G'];

  // iterating over the anonceTextElements using Array.prototype.forEach()
  // (note that this is entirely possible with NodeList.prototype.forEach(),
  // but I use Array methods on this type of collection often enough - to
  // filter, map, slice... - that I find it worth always converting to an
  // Array for further modification, but that's purely my bias):
  anonceTextElements.forEach(
    // passing the current element (not the text, the element):
    (elem) => {
      // retrieve the text of the element, using String.prototype.trim() to
      // remove leading and trailing white-space, and then trimming that to
      // to the first 50 character with String.prototype.slice():
      let text = elem.textContent.trim().slice(0, 50)
      
      // using Array.prototype.filter() to filter the Array to keep only the
      // relevant array-elements:
      logoLetters
        // we keep only the letters for which the provided assessment returns
        // true/truthy values; here we're looking to see if the retrieved
        // element text contains the current letter/company name:
        .filter((letter) => text.includes(letter))
        // the remaining elements are passed on to Array.prototype.forEach():
        .forEach(
          (matchedLetter) => {
            elem
              // here we navigate to closest ancestor element matching the '.anonce'
              .closest('.anonce')
              // from there we find the first of any elements matching the supplied
              // 'img' selector, and update/set its src property using a template-
              // literal, to interpolate the variable (matchedLetter) into the string:
              .querySelector('img').src = `img/${matchedLetter}.png`;
          });
    });
}

logo_switch();
<div >
  <h2>Job 1</h2>
  <div >
    <img >
    <p >
      A
    </p>
  </div>
</div>
<div >
  <h2>Job 2</h2>
  <div >
    <img >
    <p >
      B
    </p>
  </div>
</div>
<div >
  <h2>Job 3</h2>
  <div >
    <img >
    <p >
      C
    </p>
  </div>
</div>
<div >
  <h2>Job 4</h2>
  <div >
    <img >
    <p >
      D
    </p>
  </div>
</div>

References:

  • Related