user10279127
user10279127

Reputation:

javascript create div and append it next to a child element without id

Using the solution suggested here: https://stackoverflow.com/a/32135318/10279127 i'm trying to create a new div, and append it inside a parent div with id, next to a child <a> html element.

html:

<div id="div0">
<a href="#" class="link">anchor text</a>
// I'd like to place the new div here
</div>

js:

Element.prototype.appendAfter = function(element) {
  element.parentNode.insertBefore(this, element.nextSibling);
}, false;

var NewElement = document.createElement('div');
NewElement.id = 'newDivID';
var tToAfter = $('#div' + index + ' > a'); // this is what i tried but doesn't work
NewElement.appendAfter(tToAfter);

If inside .appendAfter(...) instead of tToAfter i write document.getElementById('randomElementId') it works and appends it, so i think must be pure javascript, is there a way in js to do something like: document.getElementById('div' + index).firstChild to get the <a> ?

Or to make it entirely with jQuery using the insertAfter (https://stackoverflow.com/a/8707793/10279127) ?

Upvotes: 0

Views: 1641

Answers (2)

benvc
benvc

Reputation: 15130

You can simplify your approach by using insertAdjacentElement. For example (the css is irrelevant - just there so you can visually see the inserted div):

const anchor = document.querySelector('#div0 a');
const elem = document.createElement('div');
elem.id = 'newDivID';
anchor.insertAdjacentElement('afterend', elem);
div:not(#div0) {
  height: 20px;
  background-color: green;
}
<div id="div0">
  <a href="#" class="link">anchor text</a>
  // I'd like to place the new div here
</div>

Upvotes: 1

Ratnamala Nallapaneni
Ratnamala Nallapaneni

Reputation: 36

you can select inside div#div0 by using

const anchor = document.querySelector("#div0>a"); 

Upvotes: 1

Related Questions