0

Today I was shortening my old codes and I saw this code:

$(".ceker").append("<a href='kit/");
$("#pdf").append("pdf");
$("#txt").append("txt");
$("#epub").append("epub");
$(".ceker").append("/7.");
$("#pdf").append("pdf");
$("#txt").append("txt");
$("#epub").append("epub");
$(".ceker").append("'><div class='menukitap'><div class='menuharry7 menuharresler'></div><h4>Ölüm Yadigarları İndir</h4></div></a>");

it used to output like that:

<a href="kit/pdf/7.pdf"><div class="menukitap"><div class="menuharry7 menuharresler"></div><h4>Ölüm Yadigarları İndir</h4></div></a>

And I made it shorter like this:

function item()
{
    if( $('.ceker').attr('id') == 'pdf' )
    {
        return "pdf";
    }
    if( $('.ceker').attr('id') == 'txt' )
    {
        return "txt";
    }
    if( $('.ceker').attr('id') == 'epub' )
    {
        return "epub";
    }
}

$(".ceker").append("<a href='kit/" + item() + "/7." + item() + "'><div class='menukitap'><div class='menuharry7 menuharresler'></div><h4>Ölüm Yadigarları İndir</h4></div></a>");

This code works too, but I don't why it does. In my opinion, this code shouldn't work because the class "ceker" has already had 3 different IDs "pdf" 'txt' and "epub"

So here's my question: How JQuery handles with getElementsByClassName Iteration (answer 1)? (I do not understand how this works if( $('.ceker').attr('id') == 'pdf' ))

And here is the HTML if you need to

<nav class="menu">
                    <span class="ara-menu-yer">Türkçe</span>
                    <a><li><section id="pdf" class="ceker"></section></li></a>
                    <a><li><section id="txt" class="ceker"></section></li></a>
                    <a><li><section id="epub" class="ceker"></section></li></a>
                    <span class="ara-menu-yer">English</span>
                    <a><li><section id="ingpdf" class="cekereng"></section></li></a>
                    <a><li><section id="ingdoc" class="cekereng"></section></li></a>
                </nav>

I'm sorry for bad spelling, grammar or vocabulary mistakes if there is. And I think that I couldn't explain my issue but I wish you can understand.

Aka
  • 79
  • 9
DifferentPseudonym
  • 1,004
  • 1
  • 12
  • 28
  • 1
    `.append()` will work on all elements in set, while getting attribute using `.attr()` will return only first matched element specific attribute. If using `.attr()` as setter, `.attr('anyattribute','anyvalue')`, then it will work on all elements in set – A. Wolff Jan 20 '15 at 17:34

1 Answers1

3

From the docs:

Get the value of an attribute for the first element in the set of matched elements.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335