Cliff T Cliff T - 2 months ago 14
jQuery Question

replaceWith does not work with child class

I cant seem to make replaceWith work with a child class. Should I do this another way?

<ul>
<li><input type="text" class="fn" value="Elvis"> <a href="#" class=".rmv" onclick="test()">test</a></li>

<li><input type="text" class="fn" value="Sam"> <a href="#" class=".rmv" onclick="test()">test</a></li>
</ul>

<script>
function test() {
$(this).find('.fn').val().replaceWith('Ted')
}
</script>

Answer

Just as sidenote - you're using the class on the anchor tags wrong - it should be

<a href="#" class="rmv">

instead of

<a href="#" class=".rmv">

As you're already using jQuery, you could just attach the click() event using jQuery like this:

$(document).ready(function () {
    $(".rmv").click(function (e) {
        e.preventDefault();
        $(this).prev('.fn').val('Ted');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
    <li>
        <input type="text" class="fn" value="Elvis" /> <a href="#" class="rmv">test</a>

    </li>
    <li>
        <input type="text" class="fn" value="Sam" /> <a href="#" class="rmv">test</a>

    </li>
</ul>

Comments