Click here to Skip to main content
Click here to Skip to main content

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

, 22 Aug 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

<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:

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.


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


About the Author

Srinivas Kalabarigi
Software Developer (Senior)
India India

Around 8 years of software development experience and involved in analysis, design, development, testing and deployment of enterprise web applications for government, healthcare and banking domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.

Educational Background
  • Post Graduation in Computer Science from Andhra University, India.
  • Graduation in Mathematics, Electronics and Computer Science from Andhra University, India.
  • Diploma in Software Technology from CMC Ltd., India.

Comments and Discussions

GeneralMy vote of 5 PinprofessionalAntariksh Verma22-Aug-13 21:15 
GeneralRe: My vote of 5 PinprofessionalSrinivas Kalabarigi26-Aug-13 9:22 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411022.1 | Last Updated 22 Aug 2013
Article Copyright 2013 by Srinivas Kalabarigi
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid