jQuery selector after dynamically created element - javascript

I am trying to get an dynamically created element using a jQuery selector but it is returning an empty array.
The first thing I am doing is grabbing an empty div:
var packDiv = document.getElementById('templates');
packDiv.innerHTML = "";
then adding items to it in a loop:
packDiv.innerHTML = packDiv.innerHTML + "<img id='" + thumbName + "' src='thumbs/" + thumbName + "'/>";
after the loop finishes I try to select an item using:
console.log($("#"+thumbName));
and it returns the empty array. All the things I search on show to use .on but all the examples show that is to set event handlers.
My question is how do I format a selector for dynamically created elements?

Assuming thumbName is a file name, for example foo.jpg, it would not be parsed by jQuery as you would expect. .jpg part of the name is treated as a class name, and since you are not providing this class name for that element, jQuery returns an empty array - it does not find anything matching your selector. You are actually searching for an element with id foo and class name jpg.
The way I would go with this is something along these lines:
var packDiv = $('#templates');
packDiv.empty();
//inside a loop
packDiv.append("<img class='" + thumbName.replace(/\./g,'') + "' src='thumbs/" + thumbName + "'/>");
console.log($("."+thumbName.replace(/\./g,'')));

Related

How to set a variable to utilize querySelectorAll to reference all elements selected by the selector [data-clue-A=clue]

I am trying to set wordLetters to reference all elements selected by the CSS selector [data-clue-A=clue] where clue is the value of data-clue-a for the object currentLetter.
I have tried:
wordLetters = document.querySelectorAll('span[data-clue-A = 'currentLetter.dataset.clueA']');
but it gives me error.
It looks like the string isn't in the right form for concatenation.
Try this:
wordLetters = document.querySelectorAll('span[data-clue-A=' + currentLetter.dataset.clueA + ']');

Appending option tags to select tag from array using JQuery

I am trying to create an options drop down list in html using JQuery to append from an Array.
Everything appears to be working correctly apart from the text between the opening & closing tags is not appearing. Am I so tired i'm missing a simple typo or doing something wrong?!?
The JS and JQuery code is:
var displayMenuSelections = function(){
var menuSelection = menu[0].prices[0];
var menuItems = Object.keys(menuSelection);
menuItems.forEach(menuFunction);
}
function menuFunction(item){
$('#menu').append($('<option value="' + item + '">' + item + '</option'));
}
The result of a typical option tag looks like this (with the 'item' missing between the opening and closing tags):
<option value="Cafe Latte"></option>
You forgot the > for the closing option tag. JQuery tries to close it for you, and in the process the inner item text doesn't get set.
Jquery takes a philosophy where it sort of tries to work with whatever you give it - this can be both good and bad, but in this case it makes it harder to debug since there's no error/exception that is raised.
var displayMenuSelections = function(){
var menuSelection = menu[0].prices[0];
var menuItems = Object.keys(menuSelection);
menuItems.forEach(menuFunction);
}
function menuFunction(item){
$('#menu').append($('<option value="' + item + '">' + item + '</option>'));
}
It looks to me like you are not passing your parameter
item
to your function
menuFunction(item)
I'm just assuming you are trying to send
var menuSelection
so you can try changing your function call to
menuItems.forEach(menuFunction(menuSelection));
I have not tested this however!

Why does jQuery not seem to add text to nested spans?

I have tried this in a couple of different orders, and neither works. I start off like this:
var messageHtml = "<span class='message-bundle' id='" + randomId + "'></span>";
$(".visualizer").append(messageHtml);
randomId is a random number. Then I set the top and left positioning for the element (it is set to position: absolute).
Then I .append() the following empty spans to this span:
$(".message-bundle#" + randomId).append("<span class='usertag' id='" + randomId + "'></span><br/>" +
"<span class='message' id='" + randomId + "'></span>");
I keep them empty initially because I want to sanitize their contents against XSS exploits. So far, everything is fine. Then I add sanitized text to these nested spans.
$(".message-bundle .usertag#" + randomId).text(msgObj.usertag);
$(".message-bundle .message#" + randomId).text(msgObj.message);
This never works. I have tried printing out the .text() of these two elements, but they contain empty strings. Why is this? Can I somehow sanitize the strings and add them inline when creating the .usertag and .message spans above (instead of using .text())?
ids need to be unique throughout the entire document, and you’re duplicating them. It’s an inappropriate use of them anyway, though; you should work with elements more and HTML less.
var message =
$('<span>', { class: 'message-bundle' })
.append($('<span>', { class: 'usertag', text: msgObj.usertag }))
.append($('<span>', { class: 'message', text: msgObj.message }));
$('.visualizer').append(message);
This appends elements that you can manipulate as proper objects from the moment they’re created, rather than by re-selecting them after adding HTML.
IDs must be unique within the document - you're assigning the same ID to multiple elements. (Or is that just over-simplified code?)

How does JQuery empty() method work?

I know that the empty method removes all children in the DOM element.
In this example however, why does removing the empty method result in duplicate entries:
and putting it in results in a normal page:
var renderNotesList = function()
{
var dummyNotesCount = 10, note, i;
var view = $(notesListSelector);
view.empty();
var ul = $("<ul id =\"notes-list\" data-role=\"listview\"></ul>").appendTo(view);
for (i=0; i<dummyNotesCount; i++)
{
$("<li>"+ "" + "<div>Note title " + i + "</div>" + "<div class=\"list-item-narrative\">Note Narrative " + i + "</div>" + "" + "</li>").appendTo(ul);
}
ul.listview();
};
I don't know why empty() doesn't work but I found this
... so until this is sorted everyone should just use:
el.children().remove(); instead of el.empty();
( jQuery.empty() does not destroy UI widgets, whereas jQuery.remove() does (using UI 1.8.4) )
Without seeing how your JavaScript is being used in your page, I suspect that you must be calling the renderNotesList() function twice and thus generating to unordered lists.
When you use the .empty() method, you are removing the first ul list, so you only see one instance. Without the call to .empty(), you retain both.
However, I can't say where or how this is happening in you web page without seeing more, but at least you now have some idea of what to look for.
Demo Fiddle
I built a demo using your JavaScript, but I was sort of guessing as to how you are using it.
Fiddle: http://jsfiddle.net/audetwebdesign/UVymE/
Footnote
It occurred to me that the function ul.listview() may actually be appending a second copy of the ul to the DOM. You need to check the code or post it for further review.

getElementById to get the ID of the element

Im currently using JSP and need to get the a cell in a table.
the following is of course in a for loop in javascript:
var cell=document.getElementById('cell_' + newRow + ',' + i);
now on variable cell I need to get the ID. Any ideas how to do that?
if i do alert(cell); then it returns this value: [object HTMLTableCellElement]
Thanks
alert(cell.id);
should work. You can find whole DOM Element attribute and method reference here:
http://www.javascriptkit.com/domref/elementproperties.shtml
try debuging it and use Watch on the newRow parameter.
as far as I know its var cell=document.getElementById('cell_' + newRow.id + ',' + i);

Categories