Click here to Skip to main content
12,350,030 members (22,806 online)
Click here to Skip to main content
Add your own
alternative version

Stats

18.3K views
1 bookmarked
Posted

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.

License

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

Share

About the Author

Srinivas Kalabarigi
Technical Lead
India India

Around 10 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.


You may also be interested in...

Comments and Discussions

 
QuestionReplace text of an HTML element Pin
vermavirender18-Aug-15 1:35
professionalvermavirender18-Aug-15 1:35 
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.

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