Jirin
Jirin

Reputation: 33

How change text in div by javascript

Please, help me :)

I have this HTML:

<div class="delivery-time">Delivery to: <strong>18.7.2018</strong></div>

How to change in Javascript to have this HTML?:

<div class="delivery-time">Ship to: <strong>18.7.2018</strong></div>

It means, have the same date in <strong>, but change text in <div> (before <strong>)

Thank you.

Upvotes: 0

Views: 118

Answers (2)

skyline3000
skyline3000

Reputation: 7913

You'll need to target the first text node in the element by using firstChild. You can change just its textContent and leave the other nodes within the element intact:

document.querySelector('.delivery-time').firstChild.textContent = 'Ship to: ';
<div class="delivery-time">Delivery to: <strong>18.7.2018</strong></div>

Upvotes: 4

Adam H
Adam H

Reputation: 1818

Even though you can't use jQuery you can still use what it's backed by, document.querySelector. So with that in mind, find your element by the class and update the innerHTML property of the element. Here is a very basic example:

var element = document.querySelector('.delivery-time')
var time = element.querySelector('strong').innerHTML
element.innerHTML = 'Ship to: <strong>' + time + '</strong>'

Upvotes: 0

Related Questions