使用querySelector遍历DOM时,如何提取指定的User Title内容?
Hey there! Let's break down how to grab that "User Title" content you need, since those dynamically-generated class names are off-limits. First, let's fix the mistake in your earlier attempt, then walk through reliable solutions.
Why Your nextSibling Attempt Failed
The issue with document.querySelector("[data-testid='people-menu'] div:nth-child(4) span:nth-child(1).nextSibling") is that you're treating nextSibling like a CSS class selector (hence the dot), but it's actually a DOM property—not part of CSS selector syntax. That's why it returned null; there's no element with a class named nextSibling.
Solution 1: Use CSS Sibling & Attribute Selectors
Since we can't rely on dynamic classes, we can target elements by their position, relationship to other elements, or existing attributes (like title).
To get the "User Title" from the title attribute:
// Target the div with the title attribute, using sibling selector to skip the first span const titleAttrElement = document.querySelector("[data-testid='people-menu'] div:nth-child(4) > span + div > div[title]"); const userTitleFromAttr = titleAttrElement.getAttribute("title"); console.log(userTitleFromAttr); // Outputs "User Title"
> span + div: Uses the adjacent sibling selector (+) to target thedivthat directly follows the firstspanchild of your initial parent div.div[title]: Targets the div that has atitleattribute (no need for the class name).
To get the "User Title" from the <p> tag:
// Target the p tag inside the second div of the sibling container const titleTextElement = document.querySelector("[data-testid='people-menu'] div:nth-child(4) > span + div > div:nth-child(2) > p"); const userTitleFromText = titleTextElement.textContent; console.log(userTitleFromText); // Outputs "User Title"
div:nth-child(2): Targets the second child div inside the sibling container (the one holding the<p>and<span>).
Solution 2: Use DOM Properties (Like nextElementSibling)
If you prefer working with DOM methods instead of pure CSS selectors, you can fetch the initial parent element first, then navigate to its siblings:
// Get your initial target div const parentDiv = document.querySelector("[data-testid='people-menu'] div:nth-child(4)"); // Get the span, then its next element sibling (skip text nodes with nextElementSibling, not nextSibling) const contentDiv = parentDiv.querySelector("span").nextElementSibling; // Option 1: Grab title attribute const attrTitle = contentDiv.querySelector("div[title]").getAttribute("title"); // Option 2: Grab text from the p tag const textTitle = contentDiv.querySelector("div:nth-child(2) > p").textContent;
- Note: Use
nextElementSiblinginstead ofnextSibling—the latter will return text nodes (like whitespace/newlines from your HTML formatting), whilenextElementSiblingtargets only actual element nodes.
Both approaches avoid dynamic class names and let you reliably extract the "User Title" content you need.
内容的提问来源于stack exchange,提问作者dikuw

