wyc
wyc

Reputation: 55293

Loop on each h2 tag inside a div

I have a structure like this:

<div class="document-content" contenteditable="true">
<h2>Heading 1</h2>
<p>Content</p>
<h2>Heading 2</h2>
<p>Content</p>
</div>

How do I loop on each of the h2 tags inside that div?

The best I could do was to find only one of the h2 tags:

$('.document-content').find('h2').html()

I need to find all so I can do stuff like adding classes or IDs to each of them.

Upvotes: 0

Views: 2671

Answers (5)

Scimonster
Scimonster

Reputation: 33409

I need to find all so I can do stuff like adding classes or IDs to each of them.

You don't even need .each() here, as the other answers have said. .html() returns the HTML content of the first element in the set. However, things like .addClass('myClass') will apply to all elements in the set. So, to add .myClass to them all, you could do:

$('.document-content h2').addClass('myClass')

(As per this answer, .find() isn't really necessary.)

Upvotes: 1

Sadikhasan
Sadikhasan

Reputation: 18600

You need each h2 tag in document-content class so you need to iterate each h2 tag using jQuery's .each() function to find all h2 tag and addClass to it.

$("div.document-content").find("h2").each(function(){
   $(this).addClass("your_class");
});

Upvotes: 0

Jerome Anthony
Jerome Anthony

Reputation: 8021

Without using the .find()

$('.document-content>h2').each(function() {
  var that = $(this);
  that.addClass('custom-class');
});
.custom-class {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="document-content" contenteditable="true">
  <h2>Heading 1</h2>
  <p>Content</p>
  <h2>Heading 2</h2>
  <p>Content</p>
</div>

Upvotes: 1

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18123

(imo) You don't need the find() function. You can use this (in combination with each())

$('.document-content h2').each( function() {
    $(this).css('color', 'red');
});

Also check this JSFiddle

Upvotes: 0

kapantzak
kapantzak

Reputation: 11750

You can use each() function:

$('.document-content').find('h2').each(function() {
  var that = $(this);
  that.addClass('custom-class');
  // more code here..
  // that.find('.another-element').addClass('test');
});
.custom-class {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="document-content" contenteditable="true">
<h2>Heading 1</h2>
<p>Content</p>
<h2>Heading 2</h2>
<p>Content</p>
</div>

Upvotes: 1

Related Questions