You've found out that basic chords are triads. That means three notes, all different. In a major triad, those notes are 1, 3 and 5 of the major scale. What you're missing is that they can be played in any order, and still make a major chord.
In closed position, they are sequential - each note is as close to the next as possible. Easy on a piano, as the notes are all there to be played. Nothing in the way. In fact, you can even play two or three of each note name, given enough fingers.In open voicings, as long as all the notes are there, they are spred out away from each other, rather than in sequential order.
The way the guitar is tuned cuts some options down in number, as it's impossible to reach certain notes while holding others down. So compromises need to happen. Yes, really with a D major chord, we need three notes, D F♯ and A. But it doesn't matter if there is one of each, or more, and the order can be changed too.
Generally speaking, on guitar, beginners are encouraged to play chords with the chord's name note as the lowest - that's called root position. The chord sounds strongest in that way, so initially, we're taught that D consists of four strings being played - as you show. Open D being the lowest. Then we have to find F♯ and A. If we played the F♯ on the D string, it would lose the open D. So we find something on the 3rd string. A is convenient. On the 2nd string, another D fits, leaving F♯ played on the top string.
You could, if you wanted it sequential, play D on 5th string 5th fret, F♯ on 4th,4th and the top three notes as before. Or play with an open A, making a second inversion of the chord. Or even press bottom string on 2nd fret, and the top three as you say, for a first inversion of D major.
To sum up - D, F♯ and A are needed for a D chord. The order doesn't matter, as long as there's one of each, minimum. On guitar, it's not always possible to play the notes in the order you'd like. In fact, sometimes, with more advanced chords, some notes have to be omitted - you just can't fit them in. But that's a story for another day.