2015-02-10 16 views
0

內的每個H2標籤我有這樣的結構:環路上的一個div

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

如何在每個分區內h2標籤的循環?

我能做的最好的是才發現h2標籤之一:

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

我需要找到所有的,所以我可以做的東西,如添加類或ID到每個人。

回答

1

可以使用each()功能:

$('.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>

+0

感謝。我很好奇爲什麼需要使用'that'? – alexchenco 2015-02-10 07:34:26

+2

設置$(this)等於那個,只有當你想在每個函數內部使用更多的$(this)對象時,爲了避免多次創建它(在我的例子中,你可以使用$(this).addClass ('class')) – kapantzak 2015-02-10 07:36:11

0

(IMO)你不需要find()功能。你可以(與each()組合)使用這個

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

還要檢查這個JSFiddle

1

如果不使用.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>

0

你需要每h2標籤document-content類,因此您需要使用jQuery的.each()函數遍歷每個h2標記以找到所有h2標記並將addClass添加到它。

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

我需要找到所有的,所以我可以做的東西,如添加類或ID到每個人。

你甚至不需要.each()在這裏,正如其他答案所說。 .html()返回集合中第一個元素的HTML內容。但是,像.addClass('myClass')之類的東西將適用於全部中的元素。因此,添加.myClass到所有這些,你可以這樣做:

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

(按this answer.find()是不是真的有必要。)