ingenious-design
ingenious-design

Reputation: 3

Adding HTML - Badges with Javascript

i wanted to add content to a customers website, depending on what css class he declares in the cms backend. So for example if he types in "Berlin", there should appear an HTML Element with the name of the city. If he types "Berlin Munich", two elements should appear and so on.

Here is my code so far:

var course = document.querySelector(".course");
var courseClass = course.className;
var locations = [
"Berlin", "Munich", "London"
];

function addLocations () {
    for(var i = 0; i < locations.length; i++) {
        if (courseClass.includes(locations[i])) {
            course.innerHTML = `<h1>${locations[i]}</h1>`
        }
    }
}

addLocations();

HTML:

<div class="ce_text course cham block">
<h2>Tierheilpraktiker</h2>
<p><strong>Komplettausbildung<br></strong><br>
beinhaltet Veterinärmedizinische Grundlagen / klassische Homöopathie nach
Hahnemann / Tierakupunktur Komplettausbildung nach TCM /
Phytotherapieausbildung (als Option mit Ausbildung Touch for Health
einzigartig in dieser Kombination)</p>
</div>

Maybe someone can help me out :)

Upvotes: 0

Views: 828

Answers (2)

marcramser
marcramser

Reputation: 589

I would do something like this:

var courses = document.getElementsByClassName("course");
var locations = ["Berlin", "Munich", "London"];
for(var i = 0; i < courses.length; i++) {
  var list = courses[i].className.split(" ");
  for(var j = 0; j < locations.length; j++) {
    if (list.includes(locations[j])) {
        courses[i].innerHTML = courses[i].innerHTML + " " + locations[j];
    }
   }
}

HTML would look like this

<ul>
  <li class="course Berlin Munich"></li>
  <li class="course Munich"></li>
</ul>

Upvotes: 1

Jayffe
Jayffe

Reputation: 1279

You can maybe split the className to make your code work :

var courseClass = course.className.split(" ");

Upvotes: 0

Related Questions