Click here to Skip to main content
15,878,814 members
Articles / Web Development / HTML
Tip/Trick

JavaScript: Replace text of an HTML element without using Id property

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
22 Aug 2013CPOL 35K   1   3
Replace text of an HTML element without using Id property.

I got a situation where I have to replace a HTML text in production environment, which is getting generated dynamically from back-end C# code and I have to do this without rebuilding and redeploying the dlls.

I wanted to do this the simplest way, by just deploying the aspx page and replacing the content using JavaScript as show in the example below:

I need to replace a heading which is in <h2>...</h2>tag:

HTML
<h2>Test - 1</h2>
<h2>Test - 2</h2>
<h2>Test - 3</h2> 

I have to replace "Test - 3" to "Test - 5". As I know the it is the 3rd <h2> element, I used the below JavaScript code:

JavaScript
var string = document.getElementsByTagName("h2")[2].innerHTML;
var replacedString = string.replace("Test - 3", "Test - 5");
document.getElementsByTagName("h2")[2].innerHTML = replacedString; 
This can also be accomplished alternatively by going through all the <h2> elements one by one and replace the  matching text using an if condition.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Program Manager
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionReplace text of an HTML element Pin
vermavirender18-Aug-15 1:35
professionalvermavirender18-Aug-15 1:35 
We have two options to replace all text from HTML with Regular Expression and without Regular Expression , see this article http://www.codeandyou.com/2015/08/replace-all-string-in-html-page-with.html[^]
GeneralMy vote of 5 Pin
Antariksh Verma22-Aug-13 20:15
professionalAntariksh Verma22-Aug-13 20:15 
GeneralRe: My vote of 5 Pin
Srinivas Kalabarigi26-Aug-13 8:22
professionalSrinivas Kalabarigi26-Aug-13 8:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.