Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to target the element above my show more button

i want to target the element above my show more button, so when i click the button more text appears i don’t want to target it by class name or id

here is my code

<div class="ccontainer" id="ccontainer">
  <p id="context"> content </p>
  <div class="img" id="cntimgcon" >
    <img src="images\image2.jpg" id="cntimgp1">
  </div>
  <p id="context"> content </p>
</div>
<Button id="showmore" onclick=" this.parentElement.style.maxHeight = 'none'"> show more </button>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t refer to the IDs that can get cumbersome. Instead give your show more button a class to refer to. That will give you the ability to add many to the same page without needing to adjust/track the IDs.

This is a basic example that toggles a class on the content div that will show the full div. Obviously the details are up to your specific needs.

Using previousElementSibling allows you to refer to the previous element.

document.addEventListener("click",function(e){
  let btn = e.target;
  if(btn.className.indexOf("showmore") > -1){
    btn.previousElementSibling.classList.toggle("active");
  }
});
.ccontainer{
 height:50px;
 overflow:hidden;
 border:1px solid #000;
 margin:10px 0;
 padding:10px;
}

.ccontainer.active{
  height:auto;
}
<div class="ccontainer">
  <p id="context"> content </p>
  <div class="img" id="cntimgcon" >
    <img src="images\image2.jpg" id="cntimgp1">
  </div>
  <p id="context"> content </p>
</div>
<Button class="showmore"> show more </button>

<div class="ccontainer">
  <p id="context"> content3 </p>
  <div class="img" id="cntimgcon" >
    <img src="images\image2.jpg" id="cntimgp1">
  </div>
  <p id="context"> content4 </p>
</div>
<Button class="showmore"> show more </button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading