Hubert S. Cumberdale Hubert S. Cumberdale - 1 month ago 12
jQuery Question

Understanding jQuery selector output

At some point in my javascript, I create a div with the following code:

var myDiv = document.createElement('div');
myDiv.className = 'square';
myDiv.id = originalID;
...
myDiv.myAttribute = myValue;


Later on, I wish to modify it, so I try to select it with this code:

$("div[myAttribute ='"+ myValue +"']")


However, I am unable to modify myDiv with this code!

$("div[myAttribute ='"+ myValue +"']").id = newID;


So I am trying to debug with this alert:

alert(JSON.stringify($("div[myAttribute ='"+ myValue +"']")));


But it shows a mess of stuff:

{

"length":0,
"prevObject":{
"0":{
"location":{
"href":"http://localhost:3000/",
"origin":"http://localhost:3000",
"protocol":"http:",
"host":"localhost:3000",
"hostname":"localhost",
"port":"3000",
"pathname":"/",
"search":"",
"hash":""
}
},
"context":{
"location":{
"href":"http://localhost:3000/",
"origin":"http://localhost:3000",
"protocol":"http:",
"host":"localhost:3000",
"hostname":"localhost",
"port":"3000",
"pathname":"/",
"search":"",
"hash":""
}
},
"length":1
},
"context":{
"location":{
"href":"http://localhost:3000/",
"origin":"http://localhost:3000",
"protocol":"http:",
"host":"localhost:3000",
"hostname":"localhost",
"port":"3000",
"pathname":"/",
"search":"",
"hash":""
}
},
"selector":"div[myAttribute='myValue']"

}


How do I form the statement to use the selector to modify that element's ID?

Answer

First thing, after creating myDiv,did you append it to the dom. Try appending it to the DOM. check the following code snippet

var myDiv = document.createElement('div');
myDiv.className = 'square';
myDiv.id = "originalID";
document.body.appendChild(myDiv)
myDiv.setAttribute('myAttribute',2);
alert(myDiv.getAttribute('myAttribute'))

Hope this helps