jQuery "get or create element" convenience method
Solution 1
You can use this poorly written code:
var $element = $('#element').length ? $('#element') : $('<div id="element"></div>').appendTo('#containerToPutIt');
Or make it a bit cleaner:
var $element = $('#element');
if(!$element.length)
$element = $('<div id="element"></div>').appendTo('#containerToPutIt');
Solution 2
There isn't really a place in jQuery where you are guaranteed to have enough information to create an element if it doesn't exist. For example, if you do $('#something')
, and you want jQuery to ensure it exists, what element do you expect jQuery to create? Where do you want it located in the DOM?
It's something you should be doing yourself with a helper method:
function getContainer() {
var container = $('.yourContainer');
if (!container.length) {
container = $('<div class="container" />').appendTo('#something');
}
return container;
}
And then use it like this:
getContainer().html('Foo Bar Baz');
getContainer().children().each(..);
Solution 3
You can just select the DOM element in jQuery and then test its length:
if ($('div.someclass').length > 0) {...}
Do NOT test for the existence of the jQuery object, since it will always return true
even if there are no DOM elements inside of it. You must always test its length.
If the length
test fails, you can then create the DOM element wherever you want using some appropriate DOM insertion method.
Solution 4
Hmm... interesting question... You might try something like.
function checkExists(selector) {
var exists = $(selector).length;
if(exists > 0) {
return $(selector);
} else {
return createElement();
}
}
Where createElement()
would be your function that makes the DOM element you are looking for. (It would return the newly created element) Then you can call it with a jquery selector like checkExists('.myClass');
for example
Related videos on Youtube
kojiro
Pythonista; Dockerista; Pyramista; Plonista; Javascriptista; CSSista; HTMLista; Webista; Shellista; you get the gista. This is my personal StackExchange account. Any opinions I express are my own, and do not reflect those of other people, even those I associate with publicly; even those of my employer. I think the above should be obvious, but people keep telling me I need to say it. How's that for an example of an opinion I clearly don't share with many employers' lawyers?
Updated on June 04, 2022Comments
-
kojiro almost 2 years
I have two functions that generate DOM elements. They both attempt to create the same container element. (I'd prefer not to enforce a specific run order for these functions, or tightly couple them to the side-effect of creating this element). I've been trying to discover a method that would get an element if it exists, or create a single instance of it if it doesn't, and return a jQuery object containing that element or all the matched elements if they already exist.
I haven't found this to exist in searching through jQuery documentation, but I thought I'd ask here to see if anyone else has encountered a similar problem and has suggestions.
-
kojiro over 12 yearsThis is a really good point. I should have mentioned that the selector in question could only sanely be element selectors, or that in some way the function would have to be given enough information to create at least a barebones element. Thanks for bringing that up!
-
Matt over 12 yearsThe first won't work as you expect as
$(...)
always returns an object (no matter whether any elements were matched), and as objects are always truthy, the results of$('#element')
will always be returned. -
Shawn Khameneh over 12 yearsYou're right, curse my laziness and lack of caffeine this morning.
-
kojiro over 12 yearsUltimately this is what I ended up doing. Thanks!
-
Simon Kenyon Shepard about 12 yearsThe first example will work, because .length returns zero, which is falsey.
-
gak over 11 yearscaffeine is always useful for answering questions on SO!