Removing elements from the DOM that were added through JS - javascript

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();

Related

Why isn't my function related to an onclick workin?

I'm studding HTML, CSS and JS and while I was creating an exercise, I was forced to stop due to an error. I created an button dynamically, setted an onclick to it and then created a function with that onclick. The problem is that the function isn't working, at leats it doesn't made anything till now.
let formularys = document.querySelector('section#formulary')
let slct = document.createElement('select')
let opts = document.createElement('option')
let optp = document.createElement('option')
let fbtn = document.querySelector('input#formularybtn')
let nbtn = document.createElement('input')
let br = document.createElement('br')
slct.id = 'pors'
slct.size = '2'
opts.value = 'rsite'
opts.innerHTML = 'Rate site'
optp.value = 'rp'
optp.innerHTML = 'Rate products'
nbtn.setAttribute('type', 'button')
nbtn.setAttribute('value', 'Next')
nbtn.setAttribute('onclick', 'nbutton')
function nbutton(){
console.log('Next working')
/*if(slct.selectedIndex == 1){
console.log('Valid rate choose')
}*/`enter code here`
}
instead of using setAttribute you can just do
nbtn.onclick = nbutton
in javascript, onclick isn't a string but a function.
The problem is, you are not appending your html code generated from JavaScript to DOM. You can either append to main DOM like below
document.body.appendChild(nbtn);
document.body.appendChild(optp);
or you can append them to some parent div by first getting div id
document.getElementById("divId").appendChild(nbtn);
where divId is id of your div where you want to add this html.
Also you should assign event listener in correct way as suggested by Tony and Rashed Rahat.
Try:
element.onclick = function() { alert('onclick requested'); };

Finding the DOM element with specific text in javascript

I know how to find specific text, but I'm really struggling to find elements with specific text
for example: <span class="foo">Special</span>
Is there example like this script below to find elemements with text?
var txt = window.document.body.innerHTML;
if (txt.match(/Special/)) {
// do something if true
alert("Found");
} else {
// do something if false
alert("Sorry");
};
You could e.g. catch every element inside your document and check if any of them contains given text.
var elems = document.querySelectorAll("*"),
res = Array.from(elems).find(v => v.textContent == 'Special');
console.log(res ? 'found!' : 'not found');
<span class="foo">Special</span>
<span class="foo">Else</span>
With pure Javascript just grab element's parent like this:
var x = this.parentElement.nodeName; //x=="span"
or
var x = this.parentElement; //x == <span> object
With jQuery just grab element's parent like this:
$(this).parents("span");
So if you add above line inside your if you can get span element as object or as text.

Wrap a tag around multiple instances of a string using Javascript

I’m trying to wrap multiple instances of a string found in html around a tag (span or abbr) using pure JS. I have found a way to do it by using the code:
function wrapString() {
document.body.innerHTML = document.body.innerHTML.replace(/string/g, ‘<tag>string</tag>');
};
but using this code messes with a link’s href or an input’s value so I want to exclude certain tags (A, INPUT, TEXTAREA etc.).
I have tried this:
function wrapString() {
var allElements = document.getElementsByTagName('*');
for (var i=0;i<allElements.length;i++){
if (allElements[i].tagName != "SCRIPT" && allElements[i].tagName != "A" && allElements[i].tagName != "INPUT" && allElements[i].tagName != "TEXTAREA") {
allElements[i].innerHTML = allElements[i].innerHTML.replace(/string/g, ‘<span>string</span>');
}
}
}
but it didn’t work as it gets ALL the elements containing my string (HTML, BODY, parent DIV etc.), plus it kept crushing my browser. I even tried with JQuery's ":containing" Selector but I face the same problem as I do not know what the string's container is beforehand to add it to the selector.
I want to use pure JavaScript to do that as I was planning on using it as a bookmark for quick access to any site but I welcome all answers regarding JQuery and other frameworks as well.
P.S. If something like that has already been answered I couldn't find it...
This is a quite complicated problem actually (you can read this detailed blog post about it).
You need to:
recurse on the dom tree
find all text nodes
do your replace on its data
make the modified data into dom nodes
insert the dom nodes to the tree, before the original text node
remove the original text node
Here is a demo fiddle.
And if you still need tagName based exclusions, look at this fiddle
The code:
function wrapInElement(element, replaceFrom, replaceTo) {
var index, textData, wrapData, tempDiv;
// recursion for the child nodes
if (element.childNodes.length > 0) {
for (index = 0; index < element.childNodes.length; index++) {
wrapInElement(element.childNodes[index], replaceFrom, replaceTo);
}
}
// non empty text node?
if (element.nodeType == Node.TEXT_NODE && /\S/.test(element.data)) {
// replace
textData = element.data;
wrapData = textData.replace(replaceFrom, replaceTo);
if (wrapData !== textData) {
// create a div
tempDiv = document.createElement('div');
tempDiv.innerHTML = wrapData;
// insert
while (tempDiv.firstChild) {
element.parentNode.insertBefore(tempDiv.firstChild, element);
}
// remove text node
element.parentNode.removeChild(element);
}
}
}
function wrapthis() {
var body = document.getElementsByTagName('body')[0];
wrapInElement(body, "this", "<span class='wrap'>this</span>");
}

Appending an element inside the child of another element

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!

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(...)

Categories