Home > OS >  How to return all unordered list items including links and links text?
How to return all unordered list items including links and links text?

Time:08-13

It takes no arguments. It returns all unordered list items (the ones that include links to Facebook, Instagram, and Twitter). They should be NodeList objects that are returned by function querySelector or querySElectorAll. Common mistake hint: we do not look only for the inner text of those items, we need NodeList objects.

MY HTML Code.

<div id="social">
    <ul>

     <li> <a  href="https://www.facebook.com">Facebook</a> </li>


     <li> <a  href="https://www.instagram.com">Instagram</a> </li> 


      <li> <a  href="https://www.twitter.com">Twitter</a> </li>

    </ul>
  </div>

MY javascript function code.

function findAllUnorderedListElements() {
  
  e = document.querySelector('#social ul a');
 
console.log(e)
}
function prepareProjects() {
}

I will be thankful to you all my friends who can help me. I need help to solve this problem.

CodePudding user response:

If I have not misunderstood, what you want is to create a list with all the social networks that appear unordered and getting the attributes of them to get the urls.

function findAllUnorderedListElements() {
  return document.querySelectorAll('#social ul a');
}
function prepareProjects() {
  let list = findAllUnorderedListElements();
  let newObject = [];

  for (let i = 0; i < list.length; i  ) {
    let item = list[i];

    newObject.push({
      url: item.href,
      label: item.innerHTML,
    });
  }

  console.log(newObject);
}

prepareProjects();
<div id="social">
  <ul>
    <li>
      <a  href="https://www.facebook.com">Facebook</a>
    </li>

    <li>
      <a  href="https://www.instagram.com"
        >Instagram</a
      >
    </li>

    <li>
      <a  href="https://www.twitter.com">Twitter</a>
    </li>
  </ul>
</div>

CodePudding user response:

To be honest, I didn't understand your question quite well, this is the solution I can give based on what I've understood.

function findAllUnorderedListElements() {
  var e = document.querySelectorAll("#social > ul > li > a");

  console.log(e);
}
findAllUnorderedListElements();
<div id="social">
  <ul>
    <li><a  href="https://www.facebook.com">Facebook</a></li>
    <li> <a  href="https://www.instagram.com">Instagram</a></li>
    <li> <a  href="https://www.twitter.com">Twitter</a> </li>
  </ul>
</div>

  • Related