How to read last element from Section in jquery

I want to check if the div having class name as "divclass" contains anchor tag, if contains I have to execute some javascript code else nothing to do.

<div class="divclass">
      <span> something text</span>
      <a href="/"> Anchor tag</a>
      <span> something text 2</span>
      <a href="/"> Anchor tag</a>
    </div>

How can we do that with jquery?

EDIT: In above HTML it has last element as anchor tag, so I want to do something code here but in below HTML I don't have anchor tag inside div so I don't want to do anything.

     <div class="divclass">
              <span> something text</span>
              <a href="/"> Anchor tag</a>
              <span> something text 2</span>
<span> something text 3</span>
            </div>

Answers


Use tagName to get name of tag. It returns name of tag in uppercase format.

Try:

$(".divclass").each(function () {
    if ($(this).find(":last").prop("tagName") == "A") {
        //do something
    }
});

DEMO here.


You can use:

if($('.divclass').has('a')) {
    ...
}

OR

if($('.divclass a').length > 0) {
    ...
}

Use the jquery last() function.

Check this demo


You need to check the if the last span in divclass has anchor tag? Right.

if($('.divclass span:last-child').find('a').length > 0) {
// your code here :)

Another alternative;

if( $('.divclass>a:last').length !== 0 ) {

A JSfiddle to test with.


Need Your Help

Best strategy for uploading multiple files

php javascript forms file-upload xmlhttprequest

I have a form to which one or more (big) files can be attached. I want to achieve the following:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.