简体   繁体   中英

javascript append at specific index document.querySelector

I am trying to create a new element and insert it inside document.querySelector('.content'); at specific index? my simple code below.

const container = document.querySelector('.content');
var counter = 0;
var p = document.createElement('p');
p.textContent = "INSERT NEW"
var buttonOne = document.createElement('button');
buttonOne.className = "btnClass";
buttonOne.innerText = "Insert";
buttonOne.onclick =  function() {
    var buttonTwo = document.createElement('button');
    buttonTwo.className = "btnClass";
    buttonTwo.innerText = "new";
    var nodes = Array.prototype.slice.call(document.getElementById('container').children);
    var index = nodes.indexOf(this);
    var c = document.createElement('p');
    c.textContent = "inserted new p";
    **container.append(c, buttonTwo, index++); <-- something like this**
};

for (let i = 0; i < 5; i++) {
    var p = document.createElement('p');
    p.textContent = "Index" + " " + i 
    container.append(p, buttonOne);
}

for example; if I have 10 buttons. Click on the 3rd, it should ADD a new element at 4th and pushes the rest. is it possible? or any other options?

Use Element.insertAdjacentHTML() could do the job for you.

The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.

I don't know how you really want to implement your code, but this is an example where I replace all your index p to a tag and when you press on any button , it will insert element after that specific element.

 const container = document.querySelector('.content'); var counter = 0; var p = document.createElement('p'); p.textContent = "INSERT NEW" var buttonOne = document.createElement('button'); buttonOne.className = "btnClass"; buttonOne.innerText = "Insert"; buttonOne.onclick = function() { var buttonTwo = document.createElement('button'); buttonTwo.className = "btnClass"; buttonTwo.innerText = "new"; var nodes = Array.prototype.slice.call(document.getElementById('container').children); var index = nodes.indexOf(this); var c = document.createElement('p'); c.textContent = "inserted new p"; }; for (let i = 0; i < 5; i++) { var p = document.createElement('button'); p.className = 'index' p.textContent = "Index" + " " + i container.append(p, buttonOne); } const allindex = document.querySelectorAll('.index') allindex.forEach((i, index) => { i.addEventListener('click', () => { allindex[index].insertAdjacentHTML("afterend", "<button>newbutton</button>") }) })
 <div class='content'></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM