[英]how can I select last loaded tag with a particular class.(not :last)
讓我們從一個例子開始:
<p class="paragraph"> some text </p>
<script> here must be the script that adds class to the above p </script>
<p class="paragraph"> some other text </p>
<script> here must be the script that adds class to the above p </script>
...
我想在“腳本”之前的“ p”中添加一個類。 腳本標記也可以位於段落中,但不應位於該段落之前。 希望現在已經清楚了,但如果不清楚,我們將很高興為您提供有關我的問題的更多信息。 提前致謝。
該腳本不知道與頁面流有關的位置。 最好的辦法是選擇所有要查找的標簽,然后選擇最后一個。
JavaScript的:
var elems = document.getElementsByClassName("paragraph");
console.log(elems[elems.length-1])
jQuery的:
$(".paragraph").last().addClass("foo");
使用getElementsByTagName並獲取返回列表的長度,它將是最后加載的標簽的索引。 例如:
<p class="paragraph"> some text </p>
<script> here must be the script that adds class to the above p </script>
<p class="paragraph"> some other text </p>
function getLastTag(){
var list=document.getElementsByTagName('p');
list[list.length-1].className='your class name';
}
您可以一次選擇所有段落,然后添加所需的類,例如,使用data屬性:
您的html:
<p class="paragraph" data-class="foo">Some text</p>
<p class="paragraph" data-class="bar">Some other text</p>
腳本的一部分(假設您在加載時使用jQuery)
$('p.paragraph').each(function () {
$(this).addClass($(this).data('class'));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.