monk
monk

Reputation: 4817

How to manipulate particular character in DOM in JavaScript?

Suppose I have text called "Hello World" inside a DIV in html file. I want to manipulate sixth position in "Hello World" text and replace that result in DOM, like using innerHTML or something like that.

The way i do is

var text = document.getElementById("divID").innerText;

now somehow I got the text and and manipluate the result using charAt for particular position and replace the result in html by replacing the whole string not just that position element. What I want to ask is do we have to every time replace the whole string or is there a way using which we can extract the character from particular position and replace the result in that position only not the whole string or text inside the div.

Upvotes: 2

Views: 350

Answers (4)

Prahalad Deshpande
Prahalad Deshpande

Reputation: 4767

Text with div's are actually text nodes and hence we will have to explicitly manipulate their content by replacing the older content with the newer one.

If you are using jQuery then you can refer to the below link for a possible technique:

[link Replacing text nodes with jQuery] http://www.bennadel.com/blog/2253-Replacing-Text-Nodes-With-jQuery.htm.

Behind the scenes, I would guess that jQuery still replaces the entire string ** for that text node**

Upvotes: 1

Daniel Imms
Daniel Imms

Reputation: 50159

If you just need to insert some text into an already existing string you should use replace(). You won't really gain anything by trying to replace only one character as it will need to make a new string anyway (as strings are immutable).

jsFiddle

var text = document.getElementById("divID").innerText;

// find and replace
document.getElementById("divID").innerText = text.replace('hello world', 'hello big world');

Upvotes: 1

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201568

Yes, you have to replace the entire string by another, since strings are immutable in JavaScript. You can in various ways hide this behind a function call, but in the end what happens is construction of a new string that replaces the old one.

Upvotes: 1

Ben Yep
Ben Yep

Reputation: 102

var newtext=text.replace(text[6],'b'); should work. Glad you asked, I didn't know that would work.

Curious that it works, it doesn't replace all instances of that character either which is odd... I guess accessing characters with bracket notation treats the character as some 'character' object, not just a string.

Don't quote me on that though.

Upvotes: 1

Related Questions