简体   繁体   中英

Replace the text inside a div

I got this snippet of code and I would like to replace the "ARRIVAL" text which is between the top and lower level <div> element but I can't figure out a way.

I don't want to use replaceWith , html or similar methods on <div class="left booktext"> because that would replace the rest of html elements. There is an event handler attached to input class="bookfields" and I don't want to lose that. Unfortunately, there is no event delegation.

<div class="left booktext">
  ARRIVAL       
  <div class="bookborder">
    <input type="hidden" name="checkin" value="2014-03-05">
    <input type="text" class="bookfields hasDatepicker" style="width:65px;" id="checkin-select" placeholder="dd/mm/yyyy">
  </div>
</div>

You can use contents() along with replaceWith() :

$('.left').contents().first().replaceWith("New Text");

Fiddle Demo

In pure Javascript:

var books = document.querySelectorAll('.booktext');
for (var i = 0, length = books.length; i < length; i++) {
    books[i].firstChild.data = "your text";
}

Easier with jQuery though:

$('.booktext').contents().first().replaceWith("your text");

Advice
Is better put text in a span element, with all the benefits of the case.
In this way you can put your text in any order inside div, like:

<div class="left booktext">
  <div class="bookborder">
    <input type="hidden" name="checkin" value="2014-03-05">
    <span>ARRIVAL</span>        
    <input type="text">
  </div>
</div>

And than replace with:

$('.bookborder span').text('my new text');

In pure javascript you can access a text node like this

var bookText = document.querySelector(".booktext");
bookText.firstChild.nodeValue = "Some other text";

see it working here
http://codepen.io/sajjad26/pen/JkAms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM