Home > Blockchain >  how to target the element above my show more button
how to target the element above my show more button

Time:07-14

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  id="ccontainer">
  <p id="context"> content </p>
  <div  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>

CodePudding user response:

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 >
  <p id="context"> content </p>
  <div  id="cntimgcon" >
    <img src="images\image2.jpg" id="cntimgp1">
  </div>
  <p id="context"> content </p>
</div>
<Button > show more </button>

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

CodePudding user response:

If your using only vanila JS you can access the previous element with the previousElementSibling property.

Example:

var showMoreButton = document.getElementById('showmore');
var previousElement = showMoreButton.previousElementSibling;

CodePudding user response:

When using jQuery you can use:

$(this).prev();   // $(this) is equal to the button
// or very specific
$(this).prev(".container"); 

Using vanilla JS you could use something like

onclick="this.previousSibling"

not sure if vanilla js has a way of selecting a previous node by identifier. Any whitespace or comment block is also considered a previousSibling, so be careful with that.

CodePudding user response:

html

<div>
<div  id="ccontainer">
  <p id="context"> content </p>
  <div  id="cntimgcon" >
    <img src="images\image2.jpg" id="cntimgp1">
  </div>
  <p id="context"> content </p>
</div>
<Button id="showmore" onclick="hideParent(this)"> show more </button>

</div>

js


function hideParent(elm){
    console.log(elm.previousElementSibling.innerHTML )
}

see https://jsfiddle.net/rkqnmv0w/

  • Related