Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append element if it doesn't exist, otherwise replace

Here's a short piece of code:

var $el = $("#something").find(".test");
if (!$el.length) {
    $("#something").append('<div class="test">somecontent</div>');
} else {
    $el.replaceWith('<div class="test">somenewcontent</div>');
}

I couldn't find a method appendOrReplaceWith or anything similar.

Any ideas how can I make it shorter?

I believe that:

$("#something").appendOrReplace('<div class="test">sometext</div>');

would be much easier to read, but no such method is available yet.

like image 689
Emil A. Avatar asked Apr 09 '14 18:04

Emil A.


3 Answers

Just remove it first then append.

$(".test").remove();
$("#something").append('<div class="test">somecontent</div>');
like image 153
sergzach Avatar answered Nov 01 '22 10:11

sergzach


Mandatory vanilla answer. It may not be shorter, but it's faster.

Get the element, grab all subelements with the class "test", create your div, check the subelements length, and if length is truthy, set the innerHTML to the div. Else, append it.

var el = document.getElementById("something");
var subel = el.getElementsByClassName("test");
var div = document.createElement("div");
div.className = "test"
if (subel.length) {
    div.textContent = "somenewcontent";
    while(el.hasChildNodes()) el.removeChild(el.lastChild); //remove child nodes
    el.appendChild(div);
} else { 
    div.textContent = "somecontent";
    el.appendChild(div);
}
like image 1
Sterling Archer Avatar answered Nov 01 '22 11:11

Sterling Archer


Adding a method like findOrAppend to jQuery could be useful:

$.fn.findOrAppend = function(selector, content) {
    var elements = this.find(selector);
    return elements.length ? elements : $(content).appendTo(this);
}

Then you can chain text, replaceWith, empty etc. as needed:

$("#something")
    .findOrAppend(".test", "<div class='test'>")
    .text("newcontent");
like image 1
fgb Avatar answered Nov 01 '22 12:11

fgb