Derek89
Derek89

Reputation: 71

How to test if this element is the first one with its class in the whole document?

I'm having troubles in coming up with a conditional to load a script.

I need a conditional that will recognize if this element is the first one in the whole document that has a certain class.

The thing is that I've done a BBCode for a phpBB forum, and I want to put all the scripts there instead of put some in the templates, but if I do that and if the BBCode is used multiple times in the same page, the scripts mess up.

For example, this is a structure:

<div>
 <div>
  <div class="some-other-stuff"></div>
 </div>
</div>

<div>
 <div>
  <div class="youtube"></div>
 </div>
</div>

<div>
 <div>
  <div class="youtube"></div>
 </div>
</div>

I want it so the script loads for the first div with the "youtube" class. I haven't managed to try anything (yep, that clueless).

This is the script I want to use the conditional for:

<script>
 $(document).ready(function() {
  $(".youtubebbcode_button").click(function() {
   $(this).siblings('.youtubevideo').stop(true, true).slideToggle("medium");
  });
 });
</script>

Upvotes: 3

Views: 59

Answers (3)

sergdenisov
sergdenisov

Reputation: 8572

You could use :eq jQuery Selector, for example:

$('.test:eq(0)').css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="test">Test 1</div>
<div class="test">Test 2</div>
<div class="test">Test 3</div>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

If the problem is that you are loading the same script block for each instance you could remove the click handler before adding it using off()

$(document).ready(function() {
  $(".youtubebbcode_button").off('click').click(function() {
   $(this).siblings('.youtubevideo').stop(true, true).slideToggle("medium");
  });
 });

then only the last instance would activate the click handler

Upvotes: 1

jfriend00
jfriend00

Reputation: 707318

You can test if a given element is the first one in the document with a given class like this:

if ($(".someClass").eq(0) === element) {
    // element is the first one in the document with .someClass
}

Or, if you just want to apply an event handler only to the first element in the document with a given class name at a specific point in time, you can just use .first() or .eq(0) directly:

// apply click handler only to first element with a a class
$(".someClass").first().click(function(e) {
    // click handler only for first element
});

Or, if you your situation is dynamic (e.g. items are being added to the page all the time and you only want the click handler to act if the element is currently the first one in the page), then you can use delegated event handling:

$(document.body).on("click", ".someClass", function(e) {
    if ($(".someClass").eq(0) === this) {
        // element clicked is the first one in the document with .someClass
    }
});

Upvotes: 1

Related Questions