Home > other >  Javascript - Show a div with a given class after clicking on a given class
Javascript - Show a div with a given class after clicking on a given class

Time:02-07

Several spans that have certain classes.

<span >1</span>
<span >2</span>
<span >4</span>
<span >4</span>

Clicking on a given <span> displays a DIV that contains the same class. How to do it?

<div >Hello!</div>
<div >Hello 2!</div>
<div >Hello 3!</div>
<div >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.

CodePudding user response:

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 >1</span>
<span >2</span>
<span >4</span>
<span >4</span>
Clicking on a given <span> displays a DIV that contains the same class. How to do it?

CodePudding user response:

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.

CodePudding user response:

var testElements = document.getElementsByClassName('click-1');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
  return testElement.nodeName === 'DIV';
});
  •  Tags:  
  • Related