In the interest of keeping a separation of concerns, here's an jQuery function that will either locate an existing element or create a new element.
So just include this jQuery anywhere:
<!-- language: lang-js -->
$.fn.upsert = function(selector, htmlString) {
// upsert - find or create new element
// find based on css selector https://api.jquery.com/category/selectors/
// create based on jQuery() http://api.jquery.com/jquery/#jQuery2
var $el = $(this).find(".message");
if ($el.length == 0) {
// didn't exist, create and add to caller
$el = $("<span class='message'></span>");
$(this).append($el);
}
return $el;
};
Then you could use like this:
<!-- language: lang-js -->
$("input[name='choice']").click(function(){
var $el = $(this).closest("form").upsert(".message", "<span class='message'></span>");
// guaranteed to have element - update if we want
$el.html("You've chosen "+this.value)
})
Ideally, it would be nice to simply pass in a selector and have jQuery create an element that matches that selector automatically, but it doesn't seem like there's a light weight vehicle for creating an element based off the CSS Selector syntax (based on Question 1 & Question 2).
Some further enhancements might provide more fine tuned control for DOM insertion instead of just always using .append()
.
<!-- begin snippet: js hide: true console: false babel: false -->
<!-- language: lang-js -->
$.fn.upsert = function(selector, htmlString) {
// upsert - find or create new element
// find based on css selector https://api.jquery.com/category/selectors/
// create based on jQuery() http://api.jquery.com/jquery/#jQuery2
var $el = $(this).find(".message");
if ($el.length == 0) {
// didn't exist, create and add to caller
$el = $("<span class='message'></span>");
$(this).append($el);
}
return $el;
};
$("input[name='choice']").click(function(){
var $el = $(this).closest("form").upsert(".message", "<span class='message'></span>");
// guaranteed to have element - update if we want
$el.html("You've chosen "+this.value)
});
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<div>
<input type="radio" id="ca" name="choice" value="A" /><label for='ca'>A</label>
<input type="radio" id="cb" name="choice" value="B" /><label for='cb'>B</label>
<input type="radio" id="cc" name="choice" value="C" /><label for='cc'>C</label>
</div>
</form>
<!-- end snippet -->