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

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.



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);



Thanks all of you following code is working for me

<script src="" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
    if ($('.toplink').length > 0) {
        $('.toplink').addClass('adin').attr('data-aid', '114');

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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.