10

I am really struggling this. I am wanting to change the src attribute of an img tag and get the error message getElementsByTagName is not a function. The following is my test markup

<html>
<body>
<div class="logo">
<img src="/a.jpg">
</div>
<script>
document.getElementsByClassName('logo').getElementsByTagName('img')[0].src ="/b.jpg";
</script>
</body>
</html>

Any advice is appreciated.

dcs
  • 155
  • 1
  • 1
  • 5

4 Answers4

18

getElementsByClassName return a collection. So you just have to do this :

document.getElementsByClassName('logo')[0].getElementsByTagName('img')[0].src ="/b.jpg";
Anthony Granger
  • 784
  • 9
  • 23
2
getElementsByClassName()

returns a collection of elements. Hence, change your code to

document.getElementsByClassName('logo')[0].getElementsByTagName('img')[0].src ="/b.jpg";//getElementsByClassName('logo')[0]

See the docs.

Zee
  • 8,420
  • 5
  • 36
  • 58
1

document.getElementsByClassName returns a list of all the classes in the document. Try the following code:

document.getElementsByClassName("logo")[0] to get the first class.

iamsankalp89
  • 4,607
  • 2
  • 15
  • 36
CosX
  • 1,920
  • 2
  • 15
  • 25
0

Elements is a live HTMLCollection of found elements.

Names is a string representing the list of class names to match; class names are separated by whitespace.

getElementsByClassName can be called on any element, not only on the document. The element on which it is called will be used as the root of the search.

document.getElementsByClassName('logo')[0].getElementsByTagName('img')[0].src ="/b.jpg";
Haresh Shyara
  • 1,826
  • 10
  • 13