通过JavaScript自动添加每个DIV的类(连续编号)? [英] adding classes (serially numbered) to each DIV on page automatically via javascript?
问题描述
问题是:是否可能通过javascript向当前网站上的每个DIV添加连续编号的类别?
感谢目前为止,我希望你得到我的意思(对不起,那个shitty的英文)! / p>
另一种方法是将回调传递给 .attr
[docs] :
$('div')。attr('class',function(i){
return'someClass'+ i;
});
尽管您也可以使用ID作为ID,因为每个类都将是唯一的。
注意,您不必使用ID或类来选择元素,有一些选择器和遍历方法,您可以获取对所需元素的引用。
防止覆盖现有类,或者只选择没有课程的元素,或以某种方式将 div
s的选择缩小到只需要的元素:
$('div:not([class])')
或使用 .addClass
[docs] 而不是 .attr
:
$('div')。addClass(function(i){
return'someClass'+ i;
});
i'm running a contact-form-plugin on my wordpress installation. everything works fine but i want to style my form a little bit more. to do it like this i have to style some DIVs (which the plugin is processing) in a different way. the problem is: all DIV-containers have no IDs or classes! everything is processed by the plugin and my PHP-skills are like zero so i have to deal with this "naked" DIVs ;-)
the question is: is it possible to add serially numbered classes to each DIV on the current site via javascript?
thanks so far and i hope you get waht i mean (sorry for that shitty english)!
Yet another way, passing a callback to .attr
[docs]:
$('div').attr('class', function(i) {
return 'someClass' + i;
});
Though you could also use this for IDs instead, since each class will be unique.
Note that you don't have to use IDs or classes to select elements, there are a number of selectors and traversal methods with which you can get a reference to the elements you want.
To prevent overriding existing classes, either select only the elements with no class or somehow narrow down the selection of div
s to only those you want:
$('div:not([class])')
or use .addClass
[docs] instead of .attr
:
$('div').addClass(function(i) {
return 'someClass' + i;
});
这篇关于通过JavaScript自动添加每个DIV的类(连续编号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!