skip to Main Content

I have this code on a website and want to change the text inside the class .payment_content but there are others with this class, so i need to point this selector by the ID #payment-option-5-container : What’s the best aproach to do this?

<div id="payment-option-5-container" class="payment-option">
<div class="payment_input">
<input type="radio" id="payment-option-5" name="payment-option" class="payment_radio not_unifrom not_uniform" data-module-name="" data-force-display="0">
<input type="hidden" id="url_module_payment_129">
                            </div>
<div class="payment_content">
<span>**Change this text**</span>
                                                            </div>
                        </div>

2

Answers


  1. Use a querySelector() where you first select by id: #payment-option-5-container and then inside (>) the class .payment_content.

    const e = document.querySelector('#payment-option-5-container > .payment_content');
    e.textContent = 'Foo Bar';
    <div class="module_payment_container">
    <div id="payment-option-5-container" class="payment-option">
       <div class="payment_input">
          <input type="radio" id="payment-option-5" name="payment-option" class="payment_radio not_unifrom not_uniform" data-module-name="" data-force-display="0">
          <input type="hidden" id="url_module_payment_129">
       </div>
       <div class="payment_content">
          <span>**Change this text**</span>
       </div>
    </div>
    Login or Signup to reply.
  2. This demo shows the effect of textContext on destroying the DOM in comparison with innerText :

    function changeTextContext() {
    const elm = document.querySelector('#payment-option-5-container > .payment_content');
    elm.textContent = 'Foo Bar';
    }
    
    function changeInnerText() {
    const elm = document.querySelector('#payment-option-5-container > .payment_content > span');
    elm.innerText = 'Foo Bar';
    }
    <div class="module_payment_container">
    <div id="payment-option-5-container" class="payment-option">
       <div class="payment_input">
          <input type="radio" id="payment-option-5" name="payment-option" class="payment_radio not_unifrom not_uniform" data-module-name="" data-force-display="0">
          <input type="hidden" id="url_module_payment_129">
       </div>
       <div class="payment_content">
          <span>**Change this text**</span>
          <p>paragraph</p>
          <h3>header 3</h3>
       </div>
    </div>
    <input type="button" value="Chane textContext of div" onclick="changeTextContext()" />
    <input type="button" value="Chane innerText of span" onclick="changeInnerText()" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search