user15097921
user15097921

Reputation:

Get child element values using javascript

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

Upvotes: 0

Views: 68

Answers (3)

muhammad mashaly
muhammad mashaly

Reputation: 1

You can use this:

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

Upvotes: 0

Aalexander
Aalexander

Reputation: 5004

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>

Upvotes: 1

Amit Saini
Amit Saini

Reputation: 595

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>

Upvotes: 0

Related Questions