添加新的类和属性的div如果它存在在页面上 [英] Add new class and attributes to div if it exists on the page
问题描述
可能重复:结果
的如何添加新的类和属性的div,如果它存在于页面
我需要它试图找到,如果一个div存在我的母版页上的JavaScript代码。如果是的话,就应该添加一个新类,并添加一个新的id属性。
为例,如果页面有这个DIV:
I need JavaScript code on my master page which tries to find if a div exists. If so, it should add a new class and also add a new id attribute. For example if the page has this div:
<div class="toplink">abc..</div>
然后JavaScript代码应该使它恰好是这样的:
Then JavaScript code should make it exactly like this:
<div class="toplink adin" data-aid="114">abc..</div>
的
DIV中的代码应该保持不变。
The code inside the div should remain the same.
我试过这段代码,但这是不工作
I tried this code but this is not working
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript">
if ($('.toplink').exists()) {
$('.toplink').addClass('adin').attr('data-aid', '114');
}
</script>
什么不对的代码?什么在哪里我把这段代码,在页眉页脚上?
我能做到这一点与JavaScript,而不是jQuery的
What wrong with this code? what where i placed this code,in header on footer? Can i do this with javascript, not jquery
推荐答案
尝试$()。length属性,并将此片段在页面的最下方,结束标记
Try $().length property instead, and place this snippet at the very bottom of the page, before closing body tag
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
if ($('.toplink').length > 0) {
$('.toplink').addClass('adin').attr('data-aid', '114');
}
});
</script>
这篇关于添加新的类和属性的div如果它存在在页面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!