This paper presents the first measurement of ψ(2S) and χc1(3872) meson production within fully reconstructed jets. Each quarkonium state (tag) is reconstructed via its decay to the J/ψ(→μ+μ−)π+π− final state in the forward region using proton-proton collision data collected by the LHCb experiment at the center-of-mass-energy of 13 TeV in 2016, corresponding to an integrated luminosity of 1.64 fb−1. The fragmentation function, presented as the ratio of the quarkonium-tag transverse momentum to the full jet transverse momentum (pT(tag)/pT(jet)), is measured differentially in pT(jet) and pT(tag) bins. The distributions are separated into promptly produced quarkonia from proton-proton collisions and quarkonia produced from displaced b-hadron decays. While the displaced quarkonia fragmentation functions are in general well described by parton-shower predictions, the prompt quarkonium distributions differ significantly from fixed-order non-relativistic QCD (NRQCD) predictions followed by a QCD parton shower.