Junaid Khan Pathan
Junaid Khan Pathan

Reputation: 127

Getting ID of list element of external HTML file using jQuery(AJAX)

I have an external HTML file which contains only an unordered list with a few list elements like this:

<ul>
    <li id="list-1"></li>
    <li id="list-2"></li>
    <li id="list-3"></li>
    <li id="list-4"></li>
    <li id="list-5"></li>
</ul>

How can I get the ID of those list elements without loading them into the DOM of my main HTML file using jQuery(AJAX).

Upvotes: 2

Views: 483

Answers (2)

Amit Arya
Amit Arya

Reputation: 142

$('button').click(function(){
$('li').each(function(){
console.log($(this).attr('id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li id="list-1">a</li>
    <li id="list-2">b</li>
    <li id="list-3">c</li>
    <li id="list-4">d</li>
    <li id="list-5">e</li>
</ul>
<button>Click Me</button>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337627

You can use AJAX to retrieve the HTML, then create a jQuery object from the returned HTML and loop through them to get their id attributes, something like this:

$.ajax({
  url: '/yourpage.html',
  success: function(html) {
    $(html).find('li').each(function() {
      var id = this.id;
      // use the id here...          
    })
  }
}); 

Alternatively you can use map() to build an array of the id values, it all depends on your use case

Upvotes: 2

Related Questions