Is there a way target an element without it's class or id

Viewed 84

I have a show more button I want to expand a div with it, I can put the button in the div and target it's parent but I don't want it to be on top of the div which I want to expand and if I put it in the end the button hides with the text, I am gonna have more than one div, and I can keep the button outside the div and target the div using it's class but the reason I am gonna have more than one div the first div will expand not matter which button I click, and I don't wanna give each div an unique class or Id and I don't want to place the button in the div I already mentioned the reason, so is there a way to directly target the div or to place button in the div and still have it to be shown on the bottom without it being hidden

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>

Someone told me to target the show more button from its Id then target it's upper sibling but it doesn't work.

1 Answers

At very first you named the Button opening tag with camelcase (first letter uppercase), the closing tag is lowercase. Second I changed the "showmore" id to class. And please see the script what I made for you.

You can remove the class of the buttons also if you using getElementsByTag("button").

const buttons = document.getElementsByClassName("showmore");
console.log(buttons);

Array.from(buttons).forEach(button => button.addEventListener("click", (e)=> {
  e.preventDefault();
  const collapse = button.previousElementSibling; //https://www.w3schools.com/jsref/prop_node_previoussibling.asp
  collapse.style.maxHeight = collapse.style.maxHeight == '0px' ? '200px' : '0px';
}));
<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 class="showmore"> show more </button>
<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 class="showmore"> show more </button>
<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 class="showmore"> show more </button>

Related