<div class="header circle">this is the header</div>
<div class"header circle"> this is the header of circle</div>
how to get the second dom that div textContent contains ‘circle’?
I do know want to get all of the doms and then for(){}
to get it.
2
Answers
You can select all html elements with class
circle
as:then, filter out elements with textContext
circle
as:In JavaScript, you usually need to retrieve all the elements that match certain criteria and then filter through them to find the specific element you are looking for. However, you can make the process more efficient by using query selectors more specifically and then filtering.
A functional approach can more concise and easier to reason about, which can lead to cleaner and more maintainable code.
In detail:
document.querySelectorAll('div.header.circle')
selects alldiv
elements with the classesheader
andcircle
. This returns a NodeList.Retrieve
div
elements with both the classesheader
andcircle
should already narrow down the number of elements you need to loop through.[...document.querySelectorAll('div.header.circle')]
creates an array from the NodeList..filter(div => div.textContent.includes('circle'))
filters the array to only includediv
elements whosetextContent
contains the word ‘circle’.This approach uses method chaining and is more concise compared to using a loop with conditionals. It is also more declarative, making it easier to understand what the code is doing. This might not work on older browser though.
It is important to understand that DOM querying and filtering are inherently procedural processes, meaning that there is no way to directly query for an element based on its
textContent
without some form of iteration. The goal is to make this process as efficient as possible by narrowing down the search criteria.The functional approach does not eliminate the procedural nature of DOM querying and filtering, but it abstracts it.
When you use
.filter()
, for example, there is still a loop happening behind the scenes, but you do not have to write the loop yourself. Instead, you provide a function that defines the criteria for filtering, and.filter()
takes care of the iteration.Warning: in the HTML code you provided, the second
div
is missing an equals sign (=
) in the class attribute. It should beclass="header circle"
instead ofclass"header circle"
. This typo could cause the code not to work as expected.