2

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..

10
  • 3
    Please show a fiddle. The code looks fine, the problem must be somewhere else Commented Feb 6, 2014 at 10:56
  • Yah, @Flixer is right Commented Feb 6, 2014 at 10:57
  • 1
    What does indexOfElement show in console? Commented Feb 6, 2014 at 10:57
  • the same code is working is reused for other codes already present. its working fine their also Commented Feb 6, 2014 at 10:58
  • 1
    Did you check the value indexOfElement ? Is is '5' when you're trying to add a class? Commented Feb 6, 2014 at 10:59

3 Answers 3

1
var menuId= 'itemMenu' + indexOfElement;
var element = document.getElementById(menuId);
element.className += ' expanded';   //note the space
Sign up to request clarification or add additional context in comments.

1 Comment

getElementById Only takes an ID. So the hash sign isn't used.
1

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.

2 Comments

how to assign the created div to a variable? other than this? var newDiv = $('<div/>').text('I am dynamic').attr('id', menuId);
This will also work var newDiv = $('<div id="'+ menuId +'">I am dynamic</div>');. How are you currently creating the DIV?
0

You might try with:

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

1 Comment

have ou included jquery file or writing the code in $(ducument).ready function() { });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.