简体   繁体   中英

How do I change a div's text content on button click? Vanilla JS/Jquery

 <div class="placeholder">
   <h3>Select</h3>
 </div>

 <div class="buttons">
   <button data-filter="*">Show all</button>
   <button data-filter=".stadia">Stadia</button>
   <button data-filter=".leisure">Leisure</button>
   <button data-filter=".heritage">Listed Heritage</button>
   <button data-filter=".residential">Residential</button>
   <button data-filter=".retail">Retail</button>
   <button data-filter=".healthcare">Healthcare</button>
   <button data-filter=".commercial">Commercial</button>
   <button data-filter=".facilities">Facilities Management</button>
   <button data-filter=".education">Education</button>
 </div>

Hello!

I would like the text in .placeholder h3 ("select") to change to the text in the selected button on click "show all" etc

I'm not overly familiar with Javascript so I don't even know where to start. I know it would be easier with an input field but this is tied into another function which I honestly don't have the ability to change.

EDIT: Eugenes answer resolved the issue, with all me having to do in the HTML is add a 'text-output' class to the h3. Thanks again!

This is what you want

Working example: https://jsfiddle.net/qt7cpaxd/

JS

buttonArray = document.querySelectorAll('button');
for (let i = 0; i < buttonArray.length; i++) {

  buttonArray[i].addEventListener('click', (e) => {
    document.querySelector('.text-output').innerText = e.target.innerText;

  })

}

HTML

<div class="placeholder">
  <h3 class="text-output">Select</h3>
</div>

<div class="buttons">
  <button data-filter="*">Show all</button>
  <button data-filter=".stadia">Stadia</button>
  <button data-filter=".leisure">Leisure</button>
  <button data-filter=".heritage">Listed Heritage</button>
  <button data-filter=".residential">Residential</button>
  <button data-filter=".retail">Retail</button>
  <button data-filter=".healthcare">Healthcare</button>
  <button data-filter=".commercial">Commercial</button>
  <button data-filter=".facilities">Facilities Management</button>
  <button data-filter=".education">Education</button>
</div>

Not in this lazy way ;) You need to give the div a ID

      <div id="ibims" class="buttons">

     function change_ibims(id, src)
         var ibims=document.getElementById(id);
         if (ibims){ // check if the element is inside the dom
            ibims.innerHTML=src;
         } 
      }

now you can find and change this div by something like

     var id="ibims";
     var src="wahtever you want";
     change_ibims(id, src);

or

     <input type="button" caption="clickme" 
     onclick="javascript:change_ibims('ibims','Hello Hello')">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM