Reputation: 22419
I have a json string
which contains HTML element. What I am trying to achieve is to fetch all anchor tag value <a>
in that string.
Json String
"content" : "<p>Reference information</p> <ul> <li><a href="https://myurl.com">My Url</a></li> <li><a
href="https://yoururl.com">Your Url</a></li> </ul>"
Here is HTML Format
<p>Reference information</p>
<ul>
<li><a href="https://myurl.com">My Url</a></li>
<li><a href="https://yoururl.com">Your Url</a></li>
</ul>
I have tried like this but cannot get exact value:
<div id="TestDiv" hidden >
</div>
let anchor = document.getElementById("TestDiv").getElementsByTagName("li");
anchor[0].innerHTML
I am getting this value
<a href="https://myurl.com">My Url</a>
But I want to get https://myurl.com
another way I tried which was closed though still has problem but don't want to use regex:
content.match(/href="([^"]*?)"/);
How can I achieve that?
Upvotes: 1
Views: 502
Reputation: 220
You can access the href attribute value using .href or using the getAttribute("href") method. However you are currently getting the li elements, but you want to instead get the anchor elements.
let anchor = document.getElementById("TestDiv").getElementsByTagName("a");
anchor[0].href;
To get all of the href's you will need to loop through the array of anchors.
var i;
for (i = 0; i < anchor.length; i++) {
anchor[i].href;
}
Upvotes: 0
Reputation: 121
You can use Array.prototype.map
like:
var anchorUrls = Array.prototype.map.call(
document.anchors, (i) => i.href;
);
console.log(anchorUrls);
Upvotes: 0
Reputation: 4873
// Create an element
const el = document.createElement("div");
// set the inner HTML
el.innerHTML = `
<p>Reference information</p>
<ul>
<li><a href="https://myurl.com">My Url</a></li>
<li><a href="https://yoururl.com">Your Url</a></li>
</ul>
`;
// grab all <a> tag
const nodeList = el.querySelectorAll("a");
// convert to array
const nodeArray = [...nodeList];
// map to href
const hrefs = nodeArray.map((a) => a.href); // ["https://myurl.com/", "https://yoururl.com/"]
Upvotes: 2