problem with getAttribute method in JS | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

problem with getAttribute method in JS

the question is asked inside the comments of the code below. please read it there https://code.sololearn.com/Wa6a13A18a8A

20th Apr 2021, 5:20 PM
salar vahidi
salar vahidi - avatar
3 Answers
+ 2
When you do `x.getAttributeNode("src").value = ...` You're changing the value property of the node returned by x.getAttributeNode(). It is a valid expression for the left-hand-side of the '=' operator. On the other hand, let's assume x has the attribute 'src' with value "hello" `x.getAttribute("src") = ...` Now, x.getAttribute("src") will return "hello". So this is the same as doing `"hello" = ....` "hello" is not a valid left-hand-side for the operator '=', and hence the whole expression is invalid. To set the attribute of an element, use the .setAttribute() method instead. So line 10 and 11 should be replaced with `x.setAttribute("src", "htt.....")` Element.setAttribute(): https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
20th Apr 2021, 5:53 PM
XXX
XXX - avatar
+ 2
salar vahidi First of all, you need to figure out whether you want to get the attribute value (see it) or set it (change it). It looks like you're trying to set the src value. In that case, you don't need to get it. All you need to do is use setAttribute("src", "new value you want"). getAttributeNode().value and getAttribute() both get you the value but but you can't use the = operator with the latter because you're just working with a simple value, not an object. So you can't set the value property. That's why setAttribute exists.
20th Apr 2021, 5:58 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 2
src: http://www.javascriptkit.com/dhtmltutors/domattribute.shtml function myFunction() { var x = document.getElementsByTagName("IMG")[0]; x.setAttribute("src", "https://cdn.pixabay.com/photo/2021/04/13/09/46/river-6175173_1280.jpg"); }
20th Apr 2021, 6:00 PM
Rohit Kh
Rohit Kh - avatar