how to capture element attribute by name inside.
how to get a href https://www.test2.com for the text "View test2"
input is "View test2" which is inside the div tag how to get output "https://www.test2.com" result using javascript
<div>
<div>
<div>
<span >
<a href="https://www.test.com">
<span dir="ltr">
<span >View test</span>
</span>
</a>
</span>
</div>
</div>
<div>
<div>
<span >
<a href="https://www.test2.com">
<span dir="ltr">
<span >View test2 </span>
</span>
</a>
</span>
</div>
</div>
</div>
CodePudding user response:
- Get all the spans that have the text.
- Loop over them.
- Find the one that matches
- Read the text.
- Compare it.
- Find the link.
- Select the attribute.
function findHref(text) {
// find the elements that have the text you are looking for
const hiddenSpans = document.querySelectorAll(".visually-hidden");
// find the element with the text you are looking for
const matchedElem = Array.from(hiddenSpans).find(
elem => elem.textContent.trim() === text
);
if (!matchedElem) {
console.error('not found');
return null;
}
// find the anchor
const anchor = matchedElem.closest('a');
// return the attribute
return anchor?.href;
}
console.log(findHref('View test2'));
console.log(findHref('View test'));
<div>
<div>
<div>
<span >
<a href="https://www.test.com">
<span dir="ltr"> <span >
<!---->View test <!----></span></span>
</a>
</span>
</div>
</div>
<div>
<div>
<span >
<a href="https://www.test2.com">
<span dir="ltr"> <span >
<!---->View test2 <!----></span></span>
</a>
</span>
</div>
</div>
</div>
CodePudding user response:
Like this
This code can have some testing added
const href = [...document.querySelectorAll('.visually-hidden')]
.find(span => span.innerText.trim() === 'View test2')
.closest('a').href;
console.log(href)
<div>
<div>
<div>
<span >
<a href="https://www.test.com">
<span dir="ltr">
<span >View test</span>
</span>
</a>
</span>
</div>
</div>
<div>
<div>
<span >
<a href="https://www.test2.com">
<span dir="ltr">
<span >View test2 </span>
</span>
</a>
</span>
</div>
</div>
</div>
