MikelG
MikelG

Reputation: 479

How to modify one element of a selected element with multiple elements within?

What I'm trying to do is grab a div, clone it, modify some of its contents, and append it. I'm having a hard time modifying some of its contents though.

Here's the selector

$('div.checkbox:first').html()

Which yields the following

<label><input type="checkbox" name="Categories[cat_name][]" value="Life" checked=""> Life</label>

How do I change "Life" to "Peace" in both locations? Mind you, it won't always be "Life".

Upvotes: 2

Views: 56

Answers (1)

Travis J
Travis J

Reputation: 82287

jsFiddle Demo

Changing the value of the input element is trivial, jQuery provides the function val for that

$('div.checkbox:first input[type="checkbox"]').val("Peace")

However, changing the text of "Life" to "Peace" is a lot harder. That is because "Life" is not inside of an element by itself, it is inside of a label which also includes an input element. In order to separate this content to change, the text nodes must be inspected. jQuery does not provide a way to do this so it must be done with native JavaScript

var div = $('div.checkbox:first');
//Change the input value to "Peace"
$('input[type="checkbox"]',div).val("Peace");

//locate the label element
var label = $('label',div);
//locate the last child of the child nodes of the label (this will be the textNode)
var labelText = label[0].childNodes[label[0].childNodes.length-1];
//assign the textNode's textContent value as "Peace" changing the text.
labelText.textContent = "Peace";

var div = $('div.checkbox:first');
$('input[type="checkbox"]',div).val("Peace");
var label = $('label',div);
var labelText = label[0].childNodes[label[0].childNodes.length-1];
labelText.textContent = "Peace";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label><input type="checkbox" name="Categories[cat_name][]" value="Life" checked=""> Life</label>
</div>

Upvotes: 2

Related Questions