Normal JavaScript ile başa ekleme ve sona ekleme nasıl uygulanır?


jQuery kullanmadan normal JavaScript ile nasıl öne ekleme (prepend) ve sona ekleme (append) yapabilirim?

Cevap #1

Başlamanız için bir parça işte burada:

theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';

// append theKid to the end of theParent
theParent.appendChild(theKid);

// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);

theParent.firstChild, theParent içindeki ilk elemana bir referans verecek ve theKid öğesini onun önüne koyacaktır.

Cevap #2

Belki de appendChild ve insertBefore DOM yöntemlerini soruyorsunuz.

parentNode.insertBefore(newChild, refChild)

newChild düğümünü, parentNode düğümünün bir çocuğu olarak, mevcut çocuk düğüm refChild'dan önce ekler. (newChild döner.)

Eğer refChild null ise, newChild çocuklar listesine listenin sonuna eklenir. Eşdeğer olarak ve daha okunabilir şekilde, parentNode.appendChild(newChild) kullanın.

Cevap #3

Bize fazla ipucu vermediniz ama sanırım sadece bir öğenin başına veya sonuna içerik eklemenin nasıl yapıldığını soruyorsunuz? Eğer öyleyse, bunu oldukça kolay bir şekilde şöyle yapabilirsiniz:

//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");

//append text
someDiv.innerHTML += "Add this text to the end";

//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;

Oldukça kolay.

Cevap #4

Her ne kadar karmaşık olursa olsun ham bir HTML dizesi eklemek istiyorsanız, uygun ilk argüman ile insertAdjacentHTML kullanabilirsiniz:

'beforebegin' Öğe öğenin kendisinden önce. 'afterbegin' Öğe içinde, ilk çocuğundan hemen önce. 'beforeend' Öğe içinde, son çocuğundan hemen sonra. 'afterend' Öğe öğenin kendisinden sonra.

İpucu: Eklenmek istenen elementi temsil eden HTML stringini almak için her zaman Element.outerHTML çağırabilirsiniz.

Kullanım örneği:

document.getElementById("foo").insertAdjacentHTML("beforeBegin",
          "<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");

DEMO

Dikkat: insertAdjacentHTML, .addEventListener ile eklenen dinleyicileri korumaz.

Cevap #5

Bunu projemde ekledim ve işe yarıyor gibi görünüyor:

HTMLElement.prototype.prependHtml = function (element) {
    const div = document.createElement('div');
    div.innerHTML = element;
    this.insertBefore(div, this.firstChild);
};

HTMLElement.prototype.appendHtml = function (element) {
    const div = document.createElement('div');
    div.innerHTML = element;
    while (div.children.length > 0) {
        this.appendChild(div.children[0]);
    }
};

Örnek :

document.body.prependHtml(`<a href="#">Hello World</a>`);
document.body.appendHtml(`<a href="#">Hello World</a>`);

İlgili makaleler