khawarPK khawarPK - 4 months ago 9
Javascript Question

How to add new class and attributes to div if it exists on the page

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.

Answer

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