georgez
georgez

Reputation: 735

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>

Upvotes: 2

Views: 1729

Answers (3)

Sajjad Ashraf
Sajjad Ashraf

Reputation: 3844

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

Upvotes: 1

SirDeveloper
SirDeveloper

Reputation: 276

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');

Upvotes: 1

Felix
Felix

Reputation: 38102

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

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

Fiddle Demo

Upvotes: 7

Related Questions