Appending an element inside the child of another element - javascript

I am trying to append a link ("a" tag) to a child of the "topBar" element.
Here is what i've got so far:
document.getElementById('topBar').innerHTML += 'Cookie Clicker Classic';
This puts the link inside the "topBar" element as a new child, but I want it inside the existing child of the "topBar" element. How do I do this? The child is just within a div tag, it has no id... I have done some reasearch on .appendChild but I haven't found any related help, thus why I am asking here...
I would be very appreciative for any ideas or even a solution to be posted.
Thanks,
Daniel
EDIT: topBar has only one child, it is nameless
also, am I doing something wrong with this?
setTimeout(doSomething, 1000);
function doSomething() {
var element = document.getElementById('particles');
if (typeof(element) != 'undefined' && element != null)
{
var newLink = document.createElement('a');
newLink.setAttribute('href', 'http://orteil.dashnet.org/experiments/cookie/');
newLink.target = 'blank';
document.getElementById('topBar').appendChild(newLink);
var del = document.getElementById('links')
del.parentNode.removeChild(del);
return;
} else {
setTimeout(doSomething, 1000);
}
}
EDIT: I have finished! Thanks to everyone for their help, especially Elias Van Ootegem. This is what I used:
var link=document.createElement('a');
link.setAttribute('href', 'http://orteil.dashnet.org/experiments/cookie/');
link.target = 'blank';
link.appendChild(
document.createTextNode('Cookie Clicker Classic')
);
var add = document.getElementsByTagName('div')[1]; //this picked the second div tag in the whole document
if(add.lastChild) add.insertBefore(link,add.lastChild); //appending it to the end of the child
else add.prependChild(link);

First, create the node:
var newLink = document.createElement('a');
//set attributes
newLink.setAttribute('href', 'http://orteil.dashnet.org/experiments/cookie/');
newLink.target = 'blank';//preferred way is using setAttribute, though
//add inner text to link:
newLink.appendChild(
document.createTextNode('Cookie Clicker Classic')//standard way, not innerHTML
);
Then, append the child, using appendChild:
document.getElementById('topBar').appendChild(newLink);
Or, given your update (your deleting some other element), use replaceChild:
document.getElementById('topBar').replaceChild(
newLink,//new
document.getElementById('links')//old, will be removed
);
And you're there!

Related

Removing elements from the DOM that were added through JS

I have tried to lookup for an answer to this but I have not been able to find an answer.
In my project, I add HTML by using JS.
let winnerHTML = 'this HTML will appear in the dom when a condition is met'
const gameCont = document.getElementById('game-container');
const decideWinner = () => {
if ( spadesPosition === 90 ||
heartsPosition === 90 ||
clubsPosition === 90 ||
diamondsPosition === 90 ) {
gameCont.insertAdjacentHTML("afterend", winnerHTML);
}
};
Now I want to remove that HTML, I've tried to set winnerHTML = ''; but clearly it's not the right logic. Since the added HTML is not part of the document, I can't select it and remove it.
Could you guys help me out here? My apologies in advance if there's already something about this but I didn't find it.
Cheers!
Add it to paragraph or span with id for later reference :
let winnerHTML = "<p id='para'>this html will appear in the dom when a condition is met<p>";
Then to remove it:
let elem=document.getElementById("para");
elem.remove();
You can also use document.createElement and store the element in a variable. Then you can use the remove function to remove it. Example
let elem = document.createElement("p");
elem.innerHTML = "Your text";
document.getElementById('game-container').appendChild(elem);
elem.remove();

What are the equivalent of after and before jQuery's function in native javascript?

I always used jQuery before, but I want to switch the following to native javascript for better performance of the website.
var first = $('ul li:first');
var first = $('ul li:last');
$(last).before(first);
$(first).after(last);
From: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/
Before (prepend):
var el = document.getElementById('thingy'),
elChild = document.createElement('div');
elChild.innerHTML = 'Content';
// Prepend it
el.insertBefore(elChild, el.firstChild);
After (append):
// Grab an element
var el = document.getElementById('thingy'),
// Make a new div
elChild = document.createElement('div');
// Give the new div some content
elChild.innerHTML = 'Content';
// Jug it into the parent element
el.appendChild(elChild);
To get the first and last li:
var lis = document.getElementById("id-of-ul").getElementsByTagName("li"),
first = lis[0],
last = lis[lis.length -1];
if your ul doesn't have an id, you can always use getElementsByTagName("ul") and figure out its index but I would advise adding an id
I guess you are looking for:
Element.insertAdjacentHTML(position, text);
Where position is:
'beforebegin'.
Before the element itself.
'afterbegin'.
Just inside the element, before its first child.
'beforeend'.
Just inside the element, after its last child.
'afterend'.
After the element itself.
And text is a HTML string.
Doc # MDN
You can use insertBefore():
var node = document.getElementById('id');
node.parentNode.insertBefore('something', node);
Documentation: insertBefore()
There is no insertAfter method. It can be emulated by combining the insertBefore method with nextSibling():
node.parentNode.insertBefore('something', node.nextSibling);

`.replaceChild()` on `this` Throwing NotFoundError: DOM Exception 8

I figured I would get fancy and use vanilla JavaScript during a jQuery event. The idea is that on click of a heading, I want to slide up a div (which works) and replace the tag clicked on to a larger heading.
From what I've read around, this can be caused by the parentNode referencing an element that's not the actual parent, but after checking it appears to be selecting the element that's directly above it.
So... here's the code!
HTML (in Jade)
.policy-container
h6.policy-heading Policies
.policy-list
.content-we-are-hiding
.not-actually-important
jQuery
$('.policy-heading').click(function() {
var self = this;
if (this.classList.contains('closed')) {
$(this).next().slideDown(300);
this.parentNode.replaceChild(self, '<h6 class="policy-heading">Policies</h6>');
} else {
$(this).next().slideUp(300);
this.parentNode.replaceChild(self, '<h2 class="policy-heading closed">Policies</h2>');
}
});
Everything seems pretty standard. Luckily I can just take care of this with jQuery, however I'd rather be using vanilla JS here. Any ideas why this isn't working?
As has been pointed out, replaceChild takes two nodes.
The following will work with native JS wrapped inside jQuery, as you've specified:
$('.policy-heading').click(function () {
var self = this,
h2 = document.createElement('h2'),
h6 = document.createElement('h6');
h2.class = "policy-heading closed";
h2.innerHTML = "Policies";
h6.class = "policy-heading";
h6.innerHTML = "Policies";
if (this.classList.contains('closed')) {
$(this).next().slideDown(300);
this.parentNode.replaceChild(h6, self);
} else {
$(this).next().slideUp(300);
this.parentNode.replaceChild(h2, self);
}
});
replaceChild takes two nodes, you are giving it a node and a string.
It looks like you'd be much better off just sticking with jQuery and using toggle functions for the sliding and class change.
try this :
.click(function(this)
you also need some debugging to understand what is going on I would advice you to use :
console.log(this)
use this :
el = document.createElement('h6');
el.class = "policy-heading";
el.innerHTML = "Policies";
this.parentNode.replaceChild(self, el);
As everyone pointed out, .replaceChild accepts two DOM elements, rather than the string like I was using. I also had its arguments backwards, the first is for the new element, the second is the replaced element.
Example code that works
$('.policy-container').on('click', '.policy-heading', function() {
var self = this,
newElement;
if (this.classList.contains('closed')) {
newElement = document.createElement( 'h6' );
newElement.classList.add('policy-heading');
newElement.innerHTML = 'Policies';
} else {
newElement = document.createElement( 'h2' );
newElement.classList.add('policy-heading');
newElement.classList.add('closed');
newElement.innerHTML = 'Policies';
}
$(this).next().slideDown(300, function() {
self.parentNode.replaceChild( newElement, self );
});
});

Issue Extracting the div tag from inside another div

HI i am working in Javascript.
My code is:
var oldData = document.getElementById(id).innerHTML;
alert(oldData);
alert is shown as : text<img src="add-icon.png"><div id = "1"></div>
Here old data contains a text an image tag and a div tag. The issue is I want to just access the div tag id but i dnt know how to get it. Please help.
Thanx in advance
The thing with using vanilla JavaScript is, you've got to write all the filters yourself :)
var oldData = document.getElementById(id), firstDiv, id;
firstDiv = filterElements(node);
id = firstDiv.id;
function filterElements( node ){
var children = parent.childElements, firstDiv, node;
for (var i = 0; i < children.length; i += 1 ){
node = children[i];
if (node.tagName && node.nodeType && node.nodeType === 1 &&
node.tagName.toLowerCase() === "div"){
firstDiv = node;
break;
}
}
return firstDiv;
}
I suggest the use of jQuery. Then you can access the id of the div within its element stored as elem as
$(elem).children("div").attr("id")
If you know the parent by ID, then you can do this:
$("#"+id).children("div").attr("id")
or even this:
$("#"+id+">div").attr("id")
Of course, if you want the ID just to access an element, then you don't need to. To append a new image to the div:
$("#"+id+">div").append("<img ...>")
or
$("#"+id+">div").append($("<img>"). ...)
Also, I recommend using classes instead of childhood to identify elements:
$("#"+id+" .image-holder").append(...)
or
$("#"+id+").find(".image-holder").append(...)

changing/stripping off url pointed by image using javascript

Might be a very simple javascript injection question, but say I have an image html tag:
<img src="rainbow.gif">
I wanted to perform a javascript, such that when clicked on the image, it doesn't go to the myfile.htm. In other words, I wanted to strip the a href which surrounds the img. How can I do this in javascript? Say that I have the following to reference the image tag:
document.elementFromPoint(%f, %f)
f can be replaced by any double/float value
If you have a reference to the img element, then its parent (parentNode) will be the link (in the structure you've given). Three options:
Remove the link entirely
Disable the link
Change the link's href
1. Remove the link entirely
You can remove the link entirely by doing this:
var link = img.parentNode,
linkParent = link.parentNode;
linkParent.insertBefore(img, link);
linkParent.removeChild(link);
That uses parentNode to find the parent and grandparent, insertBefore to move the image, and removeChild to remove the link. Note that this assumes the image is the only thing in the link.
2. Disable the link
If you want to keep the link but render it useless, you can do this:
var link = img.parentNode;
if (link.addEventListener) {
link.addEventListener("click", function(event) {
event.preventDefault();
}, false);
}
else if (link.attachEvent) {
link.attachEvent("onclick", function() {
return false;
});
}
else {
link.onclick = function() {
return false;
}
}
3. Change the href of the link:
This is trivial, just set the href property of the link element (which you can get because it's the parent node of the image) to whatever you want:
img.parentNode.href = /* ...something else */;
For instance:
img.parentNode.href = "http://stackoverflow.com";
...would change the link to point to Stack Overflow.
Live example
Some references:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Application APIs
<a id="anchorWithImage" href="myfile.htm"><img src="rainbow.gif"></a>
Why not grab the anchor, then set its href to nothing:
var a = document.getElementById("anchorWithImage");
a.href = "javascript:void(0)";
Or grab it and set its click event to cancel the default action, which is to browse to the location of its href property
a.onclick = function(e) {
e.preventDefault();
}
Or do you want to grab all anchors that have an image as their child element, and strip out their href?
jQuery would make this easy, if that's an option for you
$("a").filter(function() {
return $(this).children("a").length === 1;
}).attr("href", "javascript:void(0)");
or
$("a").filter(function() {
return $(this).children("a").length === 1;
}).click(function() { return false; }); //returning false from jQuery handlers
//prevents the default action
EDIT
If you were to have a reference to the image, and wanted to set its parent's anchor's href, you'd grab it with the parentNode property:
var img = document.getElementById("imgId");
var a = img.parentNode;
a.href = "javascript:void(0)";
With jQuery you could use something similar to this
$("a").has("img").click(function(e).preventDefaults();});
Basically all this line does is identifies all tags within the document containing an tag disables standard event process
From your comment on another answer, it sounds like you actually want to change/eliminate the target of links at a specific position in the page. You could do something like this:
var el = document.elementFromPoint(10, 10);
while(el) {
if(el.nodeName.toLowerCase() == 'a')
el.href = 'javascript:';
el = el.parentElement;
}
This would loop up from the selected element, identify if the element is an anchor, and set the href to something that does nothing.
you can change the href of a tag on window load itself, so you need not worry when it is clicked.
window.onload = fundtion(){
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
var parentElem = imgs[i].parentNode;
if(parentElem.tagName === 'A')
parentElem.setAttribute("href", "javascript:void(0)");
}
};

Categories