Reputation: 1090
I want to search words in headlines of my posts and if it contains Names example: max or Marry, it should add Photo from them.
var imageLocation = document.querySelectorAll(".summary"); // where Image should be added
var headLines = document.querySelectorAll(".ecs-thumbnail");// where my Names are.
var img = document.createElement("IMG");
headlines.forEach(function (pos){
const txt = pos.innerText;
var max = txt.includes("max");
var marry = txt.includes("marry");
if(marry === true){
pos.parentNode.childNodes[1].prepend(img);
img.setAttribute("src", "https://dev.musikzentrum-hannover.de/wp-content/uploads/marry.png");
} else if(max === true){
pos.parentNode.childNodes[1].prepend(imgAus);
img.setAttribute("src", "https://dev.musikzentrum-hannover.de/wp-content/uploads/max.png");
}
})
it Works, but I have many Headlines in the class and it adds Pictures just to the last Elements of class.
Upvotes: 0
Views: 75
Reputation: 996
There are several lines that don't look right. The if/else if test for the same condition. The same image DOM element is modified and prepended over and over again. The variable names don't match, headlines vs headLines. imageLocation is never used. This might work:
var headLines = document.querySelectorAll(".ecs-thumbnail");// where my Names are.
headLines.forEach(function (pos){
let src;
if(pos.innerText.includes("marry")){
src = "https://dev.musikzentrum-hannover.de/wp-content/uploads/marry.png";
} else if(pos.innerText.includes("max")) {
src = "https://dev.musikzentrum-hannover.de/wp-content/uploads/max.png";
}
if(src) {
let img = document.createElement("IMG");
img.setAttribute("src", src);
pos.parentNode.childNodes[1].prepend(img);
}
});
Upvotes: 1