eastboundr
eastboundr

Reputation: 1877

How to extract certain <a> elements out of a div container?

I'm on a project that requires me to extract certain <a> elements (can be in Object type) from a div container. By using JavaScript, I'm able to get all <a> objects from the div. But the problem is, I only want the objects in the "first level" of <ul>, not the ones contained in another <ul> within one of its <li>.

For example, in the code below, I only want AAA, BBB, CCC, DDD. Not CCC-sub1 nor CCC-sub2. How do I achieve this via javascript/jquery?

Help is highly appreciated! Thanks.

<div id="sampleList">

<ul>

<li>
<a href="a.html">AAA</a>
</li>

<li>
<a href="b.html">BBB</a>
</li>

<li>
<a href="c.html">CCC</a>

    <ul>
        <li>
        <a href="c-sub1.html">CCC-Sub1</a>
        </li>

        <li>
        <a href="c-sub2.html">CCC-Sub2</a>
        </li>
    </ul>

</li>


</li>
<a href="d.html">DDD</a>
</li>

</ul>

</div>

Upvotes: 0

Views: 334

Answers (2)

ValeriiVasin
ValeriiVasin

Reputation: 8716

Code:

$(function(){
  var links = $('#samplelist>ul>li>a').map(function(){
    return $(this).text();
  }).get();
  alert(links);
});

Try it.

Upvotes: 1

Paul
Paul

Reputation: 141887

Since you tagged this jQuery:

$('#sampleList > ul > li > a');

Upvotes: 4

Related Questions