javascript - How to target the second to last child's child? -


i have html this

<ul class="menu">     <li>         <a href="#1"></a>     </li>     <div></div>     <li>         <a href="#2"></a>     </li>     <div></div>     <li>         <a href="#3"></a>     </li>     <div></div>     <li>         <a href="#4"></a>     </li>     <div></div> </ul> 

i want target last link (#4) , store variable called tab. here's wrote know it's wrong

var tab = $(".menu").is(":nth-last-child(2)").children().attr("href"); 

if want anchor of second last child,

var children = $('.menu').children(); var childcount = $('.menu').children().length; var secondtolast = children[childcount - 2];  var anchor = $(secondtolast).find('[href]'); var href = anchor.attr('href'); 

var children = $('.menu').children();  var childcount = $('.menu').children().length;  var secondtolast = children[childcount - 2];    var anchor = $(secondtolast).find('[href]');  var href = anchor.attr('href');  console.log(href);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  <ul class="menu">      <li>          <a href="#1"></a>      </li>      <div></div>      <li>          <a href="#2"></a>      </li>      <div></div>      <li>          <a href="#3"></a>      </li>      <div></div>      <li>          <a href="#4"></a>      </li>      <div></div>  </ul>

otherwise, if want last anchor regardless do

var lastanchor = $('a:last'); var href = lastanchor.attr('href'); 

var lastanchor = $('a:last');  var href = lastanchor.attr('href');  console.log(href);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  <ul class="menu">    <li>      <a href="#1"></a>    </li>    <div></div>    <li>      <a href="#2"></a>    </li>    <div></div>    <li>      <a href="#3"></a>    </li>    <div></div>    <li>      <a href="#4"></a>    </li>    <div></div>  </ul>


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -