Deano
Deano

Reputation: 12190

jquery select value of child element

here is my html, I'm trying to grab the value of 'link'

<li class="nav-parent nav-expanded">
   <a>
   <i class="licon-layers" aria-hidden="true"></i>
   <span>Virtual Servers</span>
   </a>
   <ul id="vms" class="nav nav-children" style="">
      <li value="0">
         <a link="i-2-20-VM">puppet-srv2</a>
      </li>
      <li value="0">
         <a link="i-2-18-VM">puppet-srv1</a>
      </li>
      <li value="0">
         <a link="i-2-24-VM">testing</a>
      </li>
   </ul>

Here Is what I have tried so far, but it isn't working:

$("#vms").on("click", "li", function() {
   var href = $(this).children('a').find('link').attr();
    console.log(href);
});

I'm not sure what I'm doing wrong, your help is highly appreciated

Upvotes: 0

Views: 34

Answers (1)

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

You trying to find attribute link using .find('link') code. Since the child element already founded, then just capture it attribute using .attr(). Instead of that, try following code:

Change this:

var href = $(this).children('a').find('link').attr();

into

var href = $(this).children('a').attr('link');

or you can use code below also:

$("#vms").on("click", "li", function() {
  var href = $(this).find('a').attr('link');
   console.log(href);
});

AND i read your comment that sound :

I'm using that just to hold value of VM name

If so, you can add data attribute for user defined attribute like below :

<a data-link="i-2-20-VM">puppet-srv2</a>

Then to get it value, just use the .data() function like below:

var href = $(this).find('a').data('link');

Upvotes: 2

Related Questions