I'm trying to remove an element from my HTML document, which I'm able to do with the remove method, however, when console logging the NodeList with document.querySelectorAll() on some classes on elements that should've been removed, they're still showing up in the NodeList.
I need to remove an element from the webpage, but also from the NodeList, as if the element wasn't there initially on page load to prevent the rest of my application from thinking that it's there.
I would've thought that the remove method would've covered this, but unfortunately it doesn't, what am I missing and what's the workaround?
function removeElement (ident) {
const elem = document.querySelector(ident)
if (elem) {
elem.remove()
}
}
you have to get elements by their id name.
var elem = document.getElementById('myid');
elem.remove()
here 'myid' is the id of the item to be deleted.
if you want to delete it using query selector then take the help of elem's parent element.
let elem = document.querySelector(ident);
elem.parentElement.removeChild(elem);
Related
I have some <div>s where I want to append some data to a child div with a specific class but I'm not sure how to do that:
Here is my JS code:
let items = document.querySelectorAll(".item");
items.forEach(function (item) {
let textnode = document.createElement('p');
textnode.innerHTML = 'some text';
item.appendChild(textnode);
});
This actually works, bu it only appends the "textnode"-element to the existing elements.
When I try:
document.getElementsByClassName('left').appendChild(textnode);
It doesn't work.
Here is a JSFIDDLE
EDIT
I want to append the data to the .left element
It seems you want to append an element to .left descendant of item elements. If this is the case, you can use the querySelector instead of getElementsByClassName:
item.querySelector('.left').appendChild(textnode);
Note that above code calls the querySelector method as a member of item (instance of HTMLDivElement interface).
getElementsByClassName returns multiple elements. Class names are not unique. Therefore you first need to select an element in that list.
var textnode = document.createTextNode("Test");
var node = document.getElementsByClassName('left');
node[0].appendChild(textnode);
<div class="left"></div>
getElementsByClassName returns the array of elements. So u need to use the index for that.
let x = document.getElementsByClassName('left')
x[0].appendChild(textnode)
This is working.
I have updated the code in your fiddle. Please check out
what's the different between using:
// assuming using elements/tags 'span' creates an array and want to access its first node
1) var arrayAccess = document.getElementsByTagName('elementName')[0]; // also tried property items()
vs
// assuming I assign an id value to the first span element/tag
// specifically calling a node by using it's id value
2) var idAccess = document.getElementById('idValue');
then if I want to change the text node....when using example 1) it will not work, for example:
arrayAccess.firstChild.nodeValue = 'some text';
or
arrayAccess.innerText/innerHTML/textContent = 'some text';
If I "access" the node through its id value then it seems to work fine....
Why is it that when using array it does not work? I'm new to javascript and the book I'm reading does not provide an answer.
Both are working,
In your first case you need to pass the tag name instead of the element name. Then only it will work.
There might be a case that you trying to set input/form elements using innerHTML. At that moment you need to use .value instead of innerHTML.
InnerHTML should be used for div, span, td and similar elements.
So your html markup example:
<div class="test">test</div>
<div class="test">test1</div>
<span id="test">test2</span>
<button id="abc" onclick="renderEle();">Change Text</button>
Your JS code:
function renderEle() {
var arrayAccess = document.getElementsByTagName('div')[0];
arrayAccess.innerHTML = "changed Text";
var idEle = document.getElementById('test');
idEle.innerHTML = "changed this one as well";
}
Working Fiddle
When you use document.getElementsByTagName('p'), the browser traverses the rendered DOM tree and returns a node list (array) of all elements that have the matching tag.
When you use document.getElementById('something'), the browser traverses the rendered DOM tree and returns a single node matching the ID if it exists (since html ID's are unique).
There are many differences when to use which, but one main factor will be speed (getElementById is much faster since you're only searching for 1 item).
To address your other question, you already have specified that you want the first element in the returned nodeList (index [0]) in your function call:
var arrayAccess = document.getElementsByTagName('elementName')[0];
Therefore, arrayAccess is already set to the first element in the returned query. You should be able to access the text by the following. The same code should work if you used document.getElementById to get the DOM element:
console.log(arrayAccess.textContent);
Here's a fiddle with an example:
http://jsfiddle.net/qoe30w2w/
Hope this helps!
Looping through all the elements of the class, I see the code below only affecting the first element in the array yet the console log logs every one of them.
del = $('<img class="ui-hintAdmin-delete" src="/images/close.png"/>')
$('.ui-hint').each(function(){
console.log($(this));
if ($(this + ':has(.ui-hintAdmin-delete)').length == 0) {
$(this).append(del);
}
});
The elements are all very simple divs with only text inside them. They all do not have the element of the class i am looking for in my if statement, double checked that. Tried altering the statement (using has(), using children(), etc). Guess i'm missing something very simple here, haha.
Will apperciate input.
I think what you need is (also if del should be a string, if it is a dom element reference then you need to clone it before appending)
$('.ui-hint').not(':has(.ui-hintAdmin-delete)').append(function(){
//you need to clone del else the same dom reference will be moved around instead of adding new elements to each hint
return del.clone()
});
You can do this:
$('.ui-hint:not(:has(.ui-hintAdmin-delete))').append(del);
without even using the each loop here. As jquery code will internally loop through all the descendant of the ui-hint class element and append the del element only to the descendant not having any .ui-hintAdmin-delete elements.
While it would probably help to see your HTML as well, try changing your conditional to
if (!$(this).hasClass('ui-hintAdmin-delete')) {
$(this).append(del);
}
I'm dynamically creating a div like this:
var gameScoreDiv= document.createElement('div');
gameScoreDiv.innerHTML= 'Score: 0';
wrapperDiv.appendChild(gameScoreDiv);
Later I need to remove this div from DOM. How can I get rid of that div?
Is it possible to simply delete the gameScoreDiv variable and have it remove also the DOM element (I have a feeling the answer is no)?
2019 update
You can remove node with ChildNode.remove() now:
gameScoreDiv.remove()
It's supported by every major browser with the not surprising exception of IE (for which you can add a tiny polyfill though, if needed).
You can do:
gameScoreDiv.parentNode.removeChild(gameScoreDiv);
or, if you still have reference to the wrapperDiv:
wrapperDiv.removeChild(gameScoreDiv);
In jQuery it would be:
$(gameScoreDiv).remove();
but this will use the parentNode way, see the source.
You're looking for the removeChild method.
In your case I see that wrapperDiv is the parent element, so simply call it on that:
wrapperDiv.removeChild(gameScoreDiv);
Alternatively, in another scope where that isn't available, use parentNode to find the parent:
gameScoreDiv.parentNode.removeChild(gameScoreDiv);
you can give your dynamically created div an id, and later you can see if any element with this id exists, delete it. i.e.
var gameScoreDiv= document.createElement('div');
gameScoreDiv.setAttribute("id","divGameScore");
gameScoreDiv.innerHTML= 'Score: 0';
wrapperDiv.appendChild(gameScoreDiv);
and later:
var gameScoreDiv= document.getElementById('divGameScore');
wrapperDiv.removeChild(gameScoreDiv);
You can try this:
gameScoreDiv.id = "someID";
//Remove the div like this:
var element = document.getElementById('someID');
element.parentNode.removeChild(element);
<div onclick="test(this)">
Test
<div id="child">child</div>
</div>
I want to change the style of the child div when the parent div is clicked. How do I reference it? I would like to be able to reference it by ID as the the html in the parent div could change and the child won't be the first child etc.
function test(el){
el.childNode["child"].style.display = "none";
}
Something like that, where I can reference the child node by id and set the style of it.
Thanks.
EDIT: Point taken with IDs needing to be unique. So let me revise my question a little. I would hate to have to create unique IDs for every element that gets added to the page. The parent div is added dynamically. (sort of like a page notes system). And then there is this child div. I would like to be able to do something like this: el.getElementsByName("options").item(0).style.display = "block";
If I replace el with document, it works fine, but it doesn't to every "options" child div on the page. Whereas, I want to be able to click the parent div, and have the child div do something (like go away for example).
If I have to dynamically create a million (exaggerated) div IDs, I will, but I would rather not. Any ideas?
In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():
function test(el){
el.querySelector("#child").style.display = "none";
}
For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.
As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").
This works well:
function test(el){
el.childNodes.item("child").style.display = "none";
}
If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.
If the child is always going to be a specific tag then you could do it like this
function test(el)
{
var children = el.getElementsByTagName('div');// any tag could be used here..
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child') // any attribute could be used here
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}
}
document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.
edit : see this page - ids MUST be unique.
edit edit : alternate way to solve the problem :
<div onclick="test('child1')">
Test
<div id="child1">child</div>
</div>
then you just need the test() function to look up the element by id that you passed in.
If you want to find specific child DOM element use method querySelectorAll
var $form = document.getElementById("contactFrm");
in $form variable we can search which child element we want :)
For more details about how to use querySelectorAll check this page