Chrizzldi
Chrizzldi

Reputation: 561

javascript with jQuery - how to change specific Text

How can i change followed given HTML code via javascript and jQuery:

<div> <strong> unimportant text here </strong> important text here </div>

Goal is to change the Text in the <div> .... important text here </div> without touching the ...

<strong> unimportant text here </strong> 

...part

Example:

*unimportant text here * important and changed text here

Upvotes: 0

Views: 399

Answers (2)

Travis J
Travis J

Reputation: 82337

jsFiddle Demo

This requires having access to the parent div. I am not sure how you would like to access it, but for example, I will use an id.

<div id="d"> <strong> unimportant text here </strong> important text here </div>

This allows for the inner element to targeted. You should just use substring in order to select the latter part of the text

var AllText = $('#d').text();
var StrongElementText = $('#d strong').text();
var ImportantText = AllText.substr(StrongElementText.length);

Edit

With no way to target the element directly, it will have to be inferred (which can lead to target collision)

jsFiddle Demo Using Inferred target

$('div strong').each(function(){
 var AllText = this.parentNode.innerText;
 this.parentNode.innerText += " And Changed";
 var StrongElementText = this.innerText;
 var ImportantText = AllText.substr(StrongElementText.length);
 c[0].innerHTML += ImportantText + "<br>";//shows output
});

Upvotes: 1

Vural
Vural

Reputation: 8746

<div> 
    <strong> unimportant text here </strong> 
    <span id="changeText">important text here</span>
</div>

$('#changeText').text= "I CHANGE THE TEXT";

Upvotes: 0

Related Questions