Several spans that have certain classes.
<span class="1 click-1">1</span>
<span class="2 click-2">2</span>
<span class="3 click-3">4</span>
<span class="4 click-4">4</span>
Clicking on a given <span> displays a DIV that contains the same class. How to do it?
<div class="click-1">Hello!</div>
<div class="click-2">Hello 2!</div>
<div class="click-3">Hello 3!</div>
<div class="click-4">Hello 4!</div>
I need such a solution because it is development on the CMS side. User can add much more span and div. So the script has to be universal.
Looking for something like this?
document.querySelectorAll("span").forEach(e => {
e.onclick = () => { // on click on span
const div = document.createElement("div"); // create new div
div.classList = e.classList; // copy and reuse class list
div.innerText = `Hello ${e.innerText}!`; // set inner text to 'Hello ${}!'
document.body.append(div); // append div to dom
}
})
span {
display: block;
}
<span class="1 click-1">1</span>
<span class="2 click-2">2</span>
<span class="3 click-3">4</span>
<span class="4 click-4">4</span>
Clicking on a given <span> displays a DIV that contains the same class. How to do it?
Since JQuery is tagged, points to note is that only the span's 2nd class name will be used to find div with same classes in code below.
$(document).on("click","span",function(){// attaching evt listner to all spans
var getClass = $(this).prop('class').split(' ')[1];//get 2nd classname of span
$(`div.${getClass}`).show(); // divs with such class
//or
$(`.${getClass}`).show(); // anything with such class
});
This code will work with the html syntax given above. But in cases where there are just one class in a span then it will not work. So modify the code accordingly or make sure the second class of span is equal to classname of div you are trying to show.
var testElements = document.getElementsByClassName('click-1');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
return testElement.nodeName === 'DIV';
});