JQuery add element if it does not exist, otherwise replace

Here is 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 could not find the appendOrReplaceWith method or something like that.

Any ideas how I can make this shorter?

I think that:

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

it would be much easier to read, but so far this method is not available.

+4
source share
4 answers

Mandatory vanilla response. It may not be shorter, but faster.

Get an element, capture all subelements using the "test" class, create your div, check the length of the subelements, and if the length is true, set innerHTMLto div. Else, add 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);
}
+1
source

I would do it

var $s = $("#something"), $t = $s.find(".test"), c = 'New content';
( $t[0] ? $t:$s)[( $t[0] ? 'html':'append')](( $t[0] ? c :$('<div>',{class:'test'}).append(c)));
0
source

, :

var $som = $('#something');
var $ele = $(".test",$som);
var newHtml = '<div class="test">somecontent</div>';

if (!$el[0]) $som.append( newHtml );
else         $ele.replaceWith( newHtml );

( ), , , ** - , {} if else: )

0
source

Adding a jQuery method, for example findOrAppend, can be useful:

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

You can then bind text, replaceWith, emptyetc. as needed:

$("#something")
    .findOrAppend(".test", "<div class='test'>")
    .text("newcontent");
0
source

Source: https://habr.com/ru/post/1535801/


All Articles