Michael Schwartz Michael Schwartz - 7 months ago 10
Javascript Question

Change Elements HTML but Ignore Last Child

With the way I have my HTML marked up....

<textarea></textarea>
<div class="body">

<div class="content">don't change this</div>
</div>


Is it possible to change the html inside of
.body
without changing the html inside of
.content
?

EDIT:

I'm working on my code editor and my
<script>
tag in this case is replaced with
.content
, and
<body>
tag is replaced with
.body
.

The
.before
API seems to be the best solution for my case except if only 3 characters are added (ex. lol). The result in
.body
is (ex. lolollol)



$('textarea').keyup(function() {
$('.content').before(this.value)
return false
}).trigger('keyup')

textarea {
width: 98%;
height: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<div class="body">

<div class="content">don't change this</div>
</div>




Answer

This is tricky, because .body may contain text nodes.

jQuery's contents() method helps :

$('textarea').keyup(function() {
  $('.body')
    .contents()                             //get both text nodes and element nodes
    .each(function() {
      if(this.className !== 'content') {
        this.nodeValue= this.innerHTML= ''; //nodeValue needed for text nodes, 
                                            //innerHTML for element nodes
      }
    });
  
  $('.content').before(this.value);
}).trigger('keyup');
textarea {
  width: 98%;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
  <ol>
    <li>test data here</li>
  </ol>
</textarea>
<div class="body">
  
  <div class="content">don't change this</div>
</div>