0

finally started with JS and I have a question.

Why doesn't this code work (I have two images with fir and sec Ids in HTML)

function swap() {
  let x = document.getElementById("fir").src
  let y = document.getElementById("sec").src

  let z = x
  x = y
  y = z
}

But this one does

function swap() {
  let x = document.getElementById("fir")
  let y = document.getElementById("sec")

  let z = x.src

  x.src = y.src
  y.src = z
}
6
  • 1
    just a tip: [x.src, y.src] = [y.src, x.src] Commented Dec 1, 2020 at 15:26
  • Is that a way to swap two variables without using a third one? Commented Dec 1, 2020 at 15:33
  • 1
    The first code create a new src variable and change the string value without affecting the element, but the second code create a reference of the element and directly affect the src attribute. Commented Dec 1, 2020 at 15:33
  • @Orochi yes it is, you can do it for more than two also [a,b,c] = [c,b,a] it's called Destructuring assignment Commented Dec 1, 2020 at 15:39
  • this is relevant to all those "illegal invocations" you sometimes get... Commented Dec 1, 2020 at 15:42

2 Answers 2

2

It's because document.getElementById("fir").src returns the path of the image (string) whereas in the second case you are manipulating the DOM (reference). you can console log or apply break point the output in both cases and check what's happening.

Sign up to request clarification or add additional context in comments.

4 Comments

Exactly what I'm trying to explain +1
Oh so it's basically identifying the src as a string, thank you didn't know that.
yes @Orochi, and about swapping [a,b] = [b,a] checkout array destructuring ;)
0

The reason the first one doesn't work is that while you have swapped the elements that your variables point to, you haven't changed the elements themselves. There are a couple of ways of swapping the elements (one of which you already posted and test)

  1. Swap source fields
  2. Swap outerHTML (z = x.outerHTML; x = y.outerHTML; y = z.outerHtML)
  3. Move the actual elements (z = x.nextSibling; y.parentNode.insertBefore(x,y); z.parentNode.insertBefore(y,z);

Example 3 actually is incomplete: You'd also need to handle the case where there's no nextSibling. But hopefully this gives you more perspective of what attempt 1 and 2 are doing as well as how to change and manipulate elements

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.