skip to Main Content

How do i can remove the "John Doo" text in this block and then add some html content?

<label><input type="radio" name="field-value-1359303" value="Joe Doe">Joe Doe</label>

My "solution"

$('input[value="Joe Doe"]')
  .hide()
  .parents('label')
  ????
  .append('<div>my content</div>');

The end result should be as follows:

<label><input type="radio" name="field-value-1359303" value="Joe Doe"><div>my content</div></label>

2

Answers


  1. You could use vanilla javascript (not jQuery)

    NOTE: for this code to run as is you have to add id="lab" to the label element.

    1st solution (innerHTML is not the best decision)

    let label = document.getElementById('lab');
    const kid  = label.children[0];
    let new_message = "Jane Doe";
    label.innerHTML = "";
    label.appendChild(kid);
    label.innerHTML = label.innerHTML + new_message;
    

    With this solution I assume you can have access to the label element.

    2nd solution (you have to change the structure of your html)

    let label = document.getElementById('lab');
    const kid  = label.children[0];
    let span = document.createElement('span');
    let new_message = "Jane Doe";
    span.textContent = new_message;
    while (label.firstChild) {
        label.removeChild(label.firstChild);
    }
    label.appendChild(kid);
    label.appendChild(span);
    

    Personally I would go with the second solution because innerHTML can lead to problems and I don’t think an additional span would create any issues.

    Login or Signup to reply.
  2. You must declare a param to save the input, clear label body by html() before appending the input and div

    const input = $("input[value='Joe Doe']");
    $('label').html("").append(input).append('<div>my content</div>');
    <script src="https://code.jquery.com/jquery-3.6.1.slim.js"></script>
    <label><input type="radio" name="field-value-1359303" value="Joe Doe">Joe Doe</label>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search