英文:
How do I select a specific child with a common class in a unique parent in JavaScript?
问题
我想选择一个JavaScript中独特父元素的特定共同类的子元素,就像标题所说的一样。我想使用textContent
并将其附加到具有共同类的特定子元素,而不会传递到其他父元素。
我自己想了几种方法,但所有这些方法都涉及修改整个代码,从我的角度来看这非常低效。
举个例子说明我想做的事情:
我想定位task-item2
的task-title
。我可以使用querySelect
属性来实现这一点,但它最终会转到所选类的第一个(例如task-item1
的task-title
)。
是否有一种方法可以在JavaScript中实现这一点,而不必求助于独特的子类?
英文:
Just like the title says, I want to select a specific common class of a unique parent's child in JavaScript. I want to use textContent
and append that to a specific child with a common class without it going to other parents.
I've thought of several ways in my own way but all of it involves modifying the entire code which in my perspective is incredibly inefficient.
As example of what I want to do:
I want to target task-item2
's task-title
. I could do this by using the querySelect properties but it just ends up going to the first selected class as per its nature(e.g task-item1
's task-title
).
Is there a way to do this without having to resort to unique child classes in JavaScript?
<div id="task-item1">
<div class="task-checkbox"></div>
<div class="task-title"></div>
<div class="task-description"></div>
<div class="task-date"></div>
<div class="task-delete"></div>
</div>
<div id="task-item2">
<div class="task-checkbox"></div>
<div class="task-title"></div>
<div class="task-description"></div>
<div class="task-date"></div>
<div class="task-delete"></div>
</div>
答案1
得分: 2
只需链式选择器:
document.querySelector('#task-item2 .task-title').textContent = 'my title';
<div id="task-item1">
<div class="task-checkbox"></div>
<div class="task-title"></div>
<div class="task-description"></div>
<div class="task-date"></div>
<div class="task-delete"></div>
</div>
<div id="task-item2">
<div class="task-checkbox"></div>
<div class="task-title"></div>
<div class="task-description"></div>
<div class="task-date"></div>
<div class="task-delete"></div>
</div>
英文:
Just chain the selectors:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
document.querySelector('#task-item2 .task-title').textContent = 'my title';
<!-- language: lang-html -->
<div id="task-item1">
<div class="task-checkbox"></div>
<div class="task-title"></div>
<div class="task-description"></div>
<div class="task-date"></div>
<div class="task-delete"></div>
</div>
<div id="task-item2">
<div class="task-checkbox"></div>
<div class="task-title"></div>
<div class="task-description"></div>
<div class="task-date"></div>
<div class="task-delete"></div>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论