0

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 Answers2

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.

mbofos01
  • 51
  • 1
  • 1
  • 10
  • Thank you! But there's a small problem - I have a lot of elements and I don't know what content will be inside them. So I can't hardcode "jane doe" because every day there will be new content in that label. – Alexandr Timoshchuk Oct 21 '22 at 09:57
  • You can use variables, for text and other elements too. Can you be more specific on what types your content can be on? Anyhow I believe you can use this code as a base. e.g. you can add instead of a span a div with other elements inside it – mbofos01 Oct 21 '22 at 10:29
  • FYI you *can* use jquery, using `.contents()` and filter on `this.nodeType == 3` - see provided existing answer(s). – freedomn-m Oct 21 '22 at 14:39
1

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>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
yyater97
  • 1,697
  • 2
  • 9
  • 5