Olivier Pons
Olivier Pons

Reputation: 15778

This code cant find the div with a specific id

If you try this code here:

http://jsfiddle.net/8BEpZ/

I'm trying to find a div with id "test" and if I don't find, I create it. The problem is that if I call this function many times, it re-creates the div all the time:

var divClasses = $('‪#test');
if (divClasses.length==0) {
    divClasses = $('<div />', { id:"test" }).appendTo('body');
    console.log('anormal !');
}

How comes?

Upvotes: 0

Views: 162

Answers (5)

Karolis
Karolis

Reputation: 2959

Your keyboard must be producing different characters than expected, either your ' or # is incorrect. Can't figure out which one precisely since my Chrome dev tools keep crashing when playing with those characters..

You can see the difference between your '#test'

encodeURIComponent('#test')
-> "%E2%80%AA%23test"

and a #test typed in an english keyboard

encodeURIComponent('#test')
-> "%23test"

I think it's that opening quote, perhaps.

enter image description here

Upvotes: 7

Akhil
Akhil

Reputation: 1083

Solution try this

 if (!$('#test').length)  
 {    
   divClasses = $('<div />', { id:"test"}).appendTo('body');  
    console.log('anormal !');  
}

try removing that div and it should create a new one with same ID.

Upvotes: 1

enguerranws
enguerranws

Reputation: 8233

You could just change the .append() to the html() method, which fits more on what you're trying to do : http://jsfiddle.net/8BEpZ/4/

Et sinon, il faut vraiment arrêter de placer des styles directement avec JS, et encore moins des attributs de style HTML ;)

Upvotes: -1

Akhilesh
Akhilesh

Reputation: 1104

Try this:

var divClasses = $('‪#test');
if (divClasses == null) {
    divClasses = $('<div />', { id:"test" }).appendTo('body');
    console.log('anormal !');
}

Upvotes: -1

wumpz
wumpz

Reputation: 9151

I checked out your jsfiddle. After changeing single quotes to double quotes it worked.

var divClasses = $('‪#test');

to

var divClasses = $("#test");

Upvotes: 2

Related Questions