0

I am trying to replace some text in a DIV tag using JavaScript, but the tag only has a class not an ID. I have tried:

document.getElementByClassName('theClassName').innerHTML = 'text i want to insert in place of the existing text';

This has not worked, I also tried the above but using getElementById but that didn't work either.

UPDATE:

I think I need to explain more (sorry im a n00b coder). What I am doing is loading a website into a WKWebView using Swift, I am then injecting a .JS file at the end of the page loaded. Within that .JS file I am then trying to do the above with no success. I can find a DIV and hide it so far but being able to replace the text is proving hard.

Here is what I tried last but this did not work either:

var classes = document.getElementsByClassName("title-random");
for(var i=0;i<classes.length; i++) {
    if(classes[i].innerHTML == "The old text") {          
        classes[i].innerHTML = "the new text";    
        break;                                          
    }
}

I have even tried generic "find this text" and replace it code but with no effect

Baltizaar
  • 1
  • 1
  • 2
    There is no such method with name `getElementByClassName`. – Felix Kling Nov 08 '15 at 22:10
  • 1
    To enlarge on @FelixKling's answer, you need to use [`getElementsByClassName`](http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp), which returns a collection of elements. – Simon MᶜKenzie Nov 08 '15 at 23:04

1 Answers1

0

Hi if u have the class on several divs u have to access via array like this:

<!DOCTYPE html>
<html>
<body>

<div class="example">First div element with class="example".</div>

<div class="example">Second div element with class="example".</div>

<p>Click the button to change the text of the first div element with class="example" (index 0).</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>

<script>
function myFunction() {
    var x = document.getElementsByClassName("example");
    x[0].innerHTML = "Hello World!";
}
</script>

</body>
</html>
Tobias
  • 95
  • 1
  • 9