Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

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

5.00/5 (1 vote)
22 Aug 2013CPOL 35.8K  
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)