为何无法访问通过jQuery追加的children()元素?
问题原因及解决办法
你遇到的问题核心在于变量el的赋值时机错误:
- 在调用
e.append(h)之前,你就执行了var el = e.find('#span1'),此时#span1还未被添加到DOM中,所以el是一个空的jQuery对象。 - 即使后续把
h追加到e里,el依然指向之前的空对象,调用el.children()自然找不到任何元素。
修复方案
提供两种简洁的修复方式:
方式一:追加后重新获取目标元素
将el的赋值操作移到e.append(h)之后,确保拿到刚添加到DOM的元素:
$(document).ready(() => { $.each($('li.d-inline.mr4.js-post-tag-list-item'), function() { const e = $(this); const h = `<span id="span1">default color <span id="span2">blue color</span></span>`; var el = e.find('#span1'); if (el.length === 0) { e.append(h); // 追加完成后重新获取元素 el = e.find('#span1'); el.children().css({ 'color': 'blue', 'font-style': 'italic', 'font-weight': 'bold' }); console.log(el); } }); });
方式二:直接包装HTML字符串为jQuery对象
创建HTML时直接转为jQuery对象,既能提前操作样式,又能避免重复DOM查找:
$(document).ready(() => { $.each($('li.d-inline.mr4.js-post-tag-list-item'), function() { const e = $(this); // 直接将HTML字符串转为jQuery对象 const el = $(`<span id="span1">default color <span id="span2">blue color</span></span>`); if (e.find('#span1').length === 0) { // 提前设置子元素样式 el.children().css({ 'color': 'blue', 'font-style': 'italic', 'font-weight': 'bold' }); // 将处理好的元素追加到目标节点 e.append(el); console.log(el); } }); });
额外注意事项
id属性要求页面全局唯一,你循环给每个li添加#span1和#span2会导致重复id,建议替换为class(比如class="tag-text-wrap"和class="tag-highlight"),查找时用.find('.tag-text-wrap'),避免DOM结构冲突。
内容的提问来源于stack exchange,提问作者Neret
相关产品推荐
相关产品推荐

