How to add new class and attributes to div if it exists on the page [closed]
-
22-06-2021 - |
Question
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 id="Top" class="toplink">abc..</div>
Then JavaScript code should make it exactly like this:
<div id="Top" class="toplink adin" id-adi="114">abc..</div>
The code inside the div should remain the same.
Solution 4
Thanks all of you following code is working for me
<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>
answered by iamruss
As i am new to stackoverflow, i ask almost same question at Add new class and attributes to div if it exists on the page
OTHER TIPS
can't you just do:
$('#Top').addClass("toplink adin")
because if it doesn't exist, than it won't add a class.
The atrribute you are trying to set is not valid, use something like data-*
as someone said.
jQuery.fn.exists = function(){return this.length>0;}
if ($('#Top').exists()) {
$('#Top').addClass('adin').attr('data-adi', '114');
}
The id-adi
attribute is not a valid HTML attribute, but if you wish to set it anyway do:
if ($("#Top").length) {
$("#Top").addClass('adin').attr('id-adi', 114);
}