1

I still worked with getElementsByID and it was all god. But now I want to do it with ByClassName, but it doesn't work.

I want to have the temperature of this page: http://www.weatherman.com/us/ny/new-york.html the class name is: temp tempF

but this code does not work: tempString = [deg stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementByClassName('temp tempF').innerText;"]]; deg is my WebView showing the page.

Filip Radelic
  • 26,607
  • 8
  • 71
  • 97
Viper OS X
  • 291
  • 1
  • 5
  • 14

1 Answers1

6

the name of the javascript function is getElementsByClassName with an s (because in HTML, unlike ids which are unique in a given document, a class name can be attributed to multiple elements of the same page).

If you look at the source code of your page you can actually see that there are multiple elements tagged with classes temp and tempF. You need to select the right one (first? second?) depending on which one you want to extract.

For example:

tempString = [deg stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('temp tempF')[0].innerText;"];

(No need to use stringWithFormat if you don't have any format parameter, that's just overkill, simply use the string literal directly)


PS: Just to be clear about the vocabulary, note that the fact that the element is written <div class="temp tempF"> in the HTML means that this is a div element which applies two CSS distinct classes, namely temp and tempF. So this element is not "an element with the class name temp tempF" but rather "an element with two class names temp and tempF applied to it".

Tip: To debug your javascript, open the page in a browser like Chrome or Safari on your Mac, show the page inspector and go to the Console tab so you can type javascript code right here and test a bit with different expressions. In your case you would have seen that your function was mistyped, missing the "s" in the name, and once corrected you would have seen that the result of getElementsByClassName returns multiple elements and not just one.

AliSoftware
  • 32,623
  • 6
  • 82
  • 77