たとえば、まだDOMにないHTMLスニップをマージするJavaScript関数があります
<div class="one two"><input /><span name="abc">Text</span></div>
DOM ノード/タグを使用
<div id="aaa" class="another"></div>
結果は次のとおりです。
<div id="aaa" class="one two another"><input /><span name="abc">Text</span></div>
この機能を改善したい。
今まで私は次のことを行います:
最初のソース タグの class 属性を取得し、それをターゲットとマージします。
classes = $(source).first().attr("class"); this.addClass(classes);
ソースの子タグをターゲットに追加します。
this.append($(source).first().children());
今、私はこの関数に追加したい:
Take all attribute (not "class") of the first source tag and add it to the
first target tag (overwrite if it exists).
問題は、切り取られたソースがまだDOMにないため、「属性」を取得できないことです。私が今まで持っていた解決策はあまり美しくありません: 非常に一般的な属性ごとに、余分な行があります:
tabindex = $(source).first().attr("tabIndex");
this.attr("tabIndex", tabindex);
wrap = $(source).first().attr("wrap");
this.attr("wrap", wrap);
このような HTML スニペット (最初のタグ) のすべての属性を取得する方法を知っている人はいますか?
アップデート:
もちろん、ソースとターゲットを入れ替えることもできます:
- 「attributes」で対象の DOM タグのすべての属性を読み取ります。
- これらの属性を、まだ DOM にないスニペットの最初のタグに追加します。
- DOM タグを html スニペットに置き換えます。
しかし、よりエレガントなソリューションはありますか?