Pandiyan Cool
Pandiyan Cool

Reputation: 6565

addclass() working in console but not working in script

I have created a div dynamically. tried to add class as expanded through jquery its not working. But i tried the code in console, its working fine there.

code are follows:

appending element name

var menuId= '#itemMenu' + indexOfElement;

and then tried this

$(menuId).addClass('expanded');

when i tried folllowing in console

e.g. $('#itemMenu5').addClass('expanded')

its working fine..

Upvotes: 2

Views: 1951

Answers (3)

AfromanJ
AfromanJ

Reputation: 3932

You can add a class to the dynamic DIV using this example:

HTML

<div id="static">I am static</div>

CSS

.expanded {
    font-size: 20px;   
}
.never-added {
    color: red;
}

JQuery

var indexOfElement = 5;
var menuId = '#itemMenu' + indexOfElement;

//store the new DIV in a var
var newDiv = $('<div/>').text('I am dynamic').attr('id', menuId);
newDiv.insertAfter('#static');

//add the class later
newDiv.addClass('expanded');

//never added
$('#itemMenu5').addClass('never-added');

Here is a Demo

Creating a DIV dynamically then tring to apply a class to it using the ID you assigned i.e $('#itemMenu5').addClass('expanded'); won't work as the DOM does not know about the new element yet.

Assigning the new element to a variable will allow you to modify it.

EDIT:
I have added an example that shows a class of never-added which never gets aded to the new DIV.

Upvotes: 1

Vikas Gautam
Vikas Gautam

Reputation: 978

You might try with:

$("#menuId").addClass('expanded');  try directly 

Upvotes: 0

NiiL
NiiL

Reputation: 2827

var menuId= 'itemMenu' + indexOfElement;
var element = document.getElementById(menuId);
element.className += ' expanded';   //note the space

Upvotes: 1

Related Questions