EN
JavaScript / XPath - find div that contains specific class
3
points
Quick solution, XPath:
//div[contains(@class, 'my-class-name')]
Practical example:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="container">
<div class="city">San Francisco</div>
<div class="city">San Francisco</div>
<div class="city">New York</div>
<div class="city">San Francisco</div>
<div class="city">Los Angeles</div>
<div class="city">New York</div>
</div>
<script>
var container = document.querySelector('#container');
var result = document.evaluate("//div[contains(@class, 'city')]", container);
var element = null;
while (element = result.iterateNext()) {
console.log(element.textContent);
}
</script>
</body>
</html>
We should see in console all 6 cities:
San Francisco
San Francisco
New York
San Francisco
Los Angeles
New York