0

How do I get all the href values which lie under id="categoryName" using javascript?

<div class="makeStyles-categoryBreadscrumb-83" id="categoryName">
    <a href="/">Home </a><a href="/category/shoes.html">Shoes</a><a>Boots &amp; Booties</a>
</div>

Here is what I have tried:

document.getElementById("categoryName").innerHTML
2
  • using document.getElementById('categoryName').innerHTML this you can get html only. what you get ?? Commented Jan 28, 2021 at 10:12
  • get all href value Commented Jan 28, 2021 at 10:26

3 Answers 3

1

You can use .querySelectorAll("parent > child");

let elements =document.querySelectorAll("#categoryName > a");

elements.forEach((x) => {
console.log(x);
})
<div class="makeStyles-categoryBreadscrumb-83" id="categoryName">
  <a href="/">Home </a><a href="/category/shoes.html">Shoes</a><a>Boots &amp; Booties</a>
  <a href="/">Bla </a><a href="/category/shoes.html">Shoes</a><a>Boots &amp; Booties</a>
</div>

Sign up to request clarification or add additional context in comments.

5 Comments

document.querySelectorAll("categoryName > a"); can i use this ?
yes but categoryName is an id so you have to select it by using a # before. #categoryName
document.getElementById("categoryName > a ") Is this ok ?
No it isn't getElementById is looking for an element by an id. Use querySelectorAll here
document.querySelectorAll("#categoryName > a");this is how you can use it
0

You can your result with the help of querySelectorAll.

var x = document.querySelectorAll("#categoryName > a");

x.forEach((x) => {
  if(x.href) {
    console.log(x.href);
  }
})
<div class="makeStyles-categoryBreadscrumb-83" id="categoryName">
    <a href="/">Home </a><a href="/category/shoes.html">Shoes</a><a>Boots &amp; Booties</a>
</div>

Comments

0

You can use this:

let x =document.getElementById('parent').children
for (i = 0; i < x.length; i++) {
  console.log(x.item(i).href)
}

1 Comment

Hey muhammad, welcome to Stack Overflow! Good work providing a possible solution, but try to elaborate on why this solution works, what it does. You can do this by editing your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.