Remove element from DOM [duplicate] - javascript

This question already has answers here:
JavaScript DOM remove element
(4 answers)
Closed 8 years ago.
I have a code:
<ul class='mates'>
<li class='m' id='1'>Jakub</li>
<li class='f' id='2'>Vinnie</li>
<li class='m' id='3'>David</li>
</ul>
This script selects one of the 'li' elements, according to users input:
<script>
var mates = document.getElementsByClassName('mates')[0];
for (var i=0; i< mates.childNodes.length; i++){
if(mates.children[i].innerHTML == 'Vinnie') alert("Got you! ID "+mates.children[i].id)
}
</script>
And I need to remove this element:
<script>
var mates = document.getElementsByClassName('mates')[0];
for (var i=0; i< mates.childNodes.length; i++){
if(mates.children[i].innerHTML == 'Vinnie') {
alert("Got you! ID "+mates.children[i].id);
parent = document.getElementsByClassName('mates');
mateToDelete = mates.children[i];
parent.removeChild(mateToDelete);
}
}
</script>
This is what I tried in several different ways but I always got error, e.g. " Cannot call method 'removeChild' of undefined". Any ideas?

You already have the parent node from your original getElementsByClassName, and you have your child through the loop that you've just performed.
As such, it's simple:
for (var i=0; i< mates.childNodes.length; i++){
if(mates.children[i].innerHTML == 'Vinnie'){
alert("Got you! ID "+mates.children[i].id)
mates.removeChild(mates.children[i]);
break;
}
}
For the sake of completeness (and to prevent further arguing in comments :P), if you are in fact potentially deleting multiple "Vinnie"'s from your list, then it would be better to make a list of those children you want to delete, then delete them after like so:
var toDelete=[],
i;
for (i=0; i< mates.childNodes.length; i++){
if(mates.children[i].innerHTML == 'Vinnie'){
alert("Got you! ID "+mates.children[i].id)
toDelete.push(mates.children[i]);
}
}
for (i=0; i<toDelete.length; i++){
mates.removeChild(toDelete[i]);
}

You don't need that parent variable. Delete it using this:
mates.removeChild(mateToDelete);
Fiddle: http://jsfiddle.net/3XeM5/2/
I also modified your for-loop to use:
for (var i=0; i< mates.children.length; i++){
The length of this (children.length) is 3, the length of childNodes is 7, so if nothing is found the loop will break!
Edit: If you want to delete multiple iterations of a specific element, remove the break; in the if-logic. If you're only looking for the first, leave the break.

Use This:
mates.removeChild(mates.children[i]);
Example:
http://jsfiddle.net/t9nCT/1/

You're retrieving a collection, so do,
parent[0].removeChild(mateToDelete);

Related

Why appending a div using html and jquery variable has different outputs?

Trying to solve a practice related to javaScript and JQuery, and have met an issue which I could not identify.
I created a variable to store a div, and tried to create multiple instances of it as follows:
(there is a logical mistake I have in inner loop related to the number of appended defineBox objects but this is something I am
working on separately,not related to this topic)
$("#wrapper").empty();
var lineBox=document.createElement('div');
for(var i=0; i<size; i++){
$('#wrapper').append('lineBox');
for(var j=0; j<size; j++){
$("#wrapper > div ").append(defineBox(boxSize));
}
}
When the code is executed, it shows only one "lineBox" div in html document. defineBox is appended to the lineBox div.
When I use the following code instead, it displays "i" times of 'div' just as expected from the loop and each 'div' includes 'defineBox's.
for(var i=0; i<size; i++){
$('#wrapper').append('<div></div>');
for(var j=0; j<size; j++){
$("#wrapper > div ").append(defineBox(boxSize));
}
}
I thought creating a var with document.createElement('div') would have the same result as '<div></div>'. Where does the difference come from?
Try the jQuery's .clone() method. You're creating one instanced of the div in the dom.
$("#wrapper").empty();
var lineBox=document.createElement('div');
$('#wrapper').append(lineBox);
for(var i=0; i<size-1; i++){
$('#wrapper').append(lineBox.clone());
for(var j=0; j<size; j++){
$("#wrapper > div ").append(defineBox(boxSize));
}
}
Here is the documentation for the clone method of jQuery:
https://api.jquery.com/clone/
Each time this expression called
$('#wrapper').append('<div></div>');
jQuery creates a new div element. In the first example you've shared, new div element created just once with var lineBox=document.createElement('div');

Dynamically bond handler on multiple elements will call only last bond function

http://jsfiddle.net/7CV88/8/
On this snippet, I try to bind change to #r(Nth)e <input> element to change the contents of #r(N+1th)s <input> element. But when I change any Nth <input> element, the message shown is always "#r(last N)e change handler"
for(var i = 1; i < numRanges; i++){
$('#r'+i+'e').change(function(){
$('#messages').html('#r'+i+'e change handler');
$('#r'+(i+1)+'s').val($('#r'+i+'e').val());
});
}
You should use the so-called event data to pass the value of i into the onchange event handler:
for(var i = 1; i < numRanges; i++){
$('#r'+i+'e').change(i, function(e){
$('#messages').html('#r'+e.data+'e change handler');
$('#r'+(e.data+1)+'s').val($('#r'+e.data+'e').val());
});
}
Updated Demo.
Note: This just answers directly to your asked problem, I know your code is messy, fixing it is not the main thing to do.
This is a typical "closure" issue.
I was trying the simplest way to get out of the closure issue so I suggested this incorrect way:
for(var i = 1; i < numRanges; i++){
$('#r'+i+'e').change(function(){
var tempVariable = i;
$('#messages').html('#r'+tempVariable +'e change handler');
$('#r'+(tempVariable +1)+'s').val($('#r'+tempVariable +'e').val());
});
}
Thanks to metadings, I realized my mistake so I created a demo to test according to their advice:
var list = $("div");
for(var i = 0; i < list.length; i++){
$(list[i]).click((function(x){
return function(){alert(x);};
})(i));
}
http://jsfiddle.net/9qBXn/
HTH

Access dynamic generated div id

I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}​
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.

Javascript If List Element contains 'Whatever', don't display

I've got some code in html like
<li id="1"></li>
<li id="2">Whatever</li>
<li id="3"></li>
Is there any way I can make it so that if the li contains a piece of text, it won't be displayed, yet all the other lis will be unaffected?
You could loop through your lis and use document.getElementById(id).innerHTML to get the value inside it to compare to, and if so, use document.getElementById(id).style.display = 'none';
var list = document.getElementsByTagName("li");
for(var i = 0; i < list.length; i++){
if(list[i].textContent === "Whatever"){
list[i].style.display = "none";
}
}
Live Demo
Here's a couple of examples using exact/non-exact matches, case-sensitive and insensitive.
http://jsfiddle.net/ZgrzL/
Edit: wow, I'm slow.

Javascript - Link Name Changing with restrictions

I'm trying to change the name of a link, however, I have some restrictions. The link is placed in code that looks like this:
<li class='time'>
Review Time
<img alt="Styled" src="blah" />
</li>
Basically, I have a class name to work with. I'm not allowed to edit anything in these lines, and I only have a header/footer to write Javascript / CSS in. I'm trying to get Review Time to show up as Time Review, for example.
I know that I can hide it by using .time{ display: hide} in CSS, but I can't figure out a way to replace the text. The text is also a link, as shown. I've tried a variety of replace functions and such in JS, but I'm either doing it wrong, or it doesn't work.
Any help would be appreciated.
You could get the child elements of the li that has the class name you are looking for, and then change the innerHTML of the anchor tags that you find.
For example:
var elements = document.getElementsByClassName("time")[0].getElementsByTagName("a");
for(var i = 0, j = elements.length; i<j; i++){
elements[i].innerHTML = "Time Review";
}
Of course, this assumes that there is one element named "time" on the page. You would also need to be careful about checking for nulls.
Split the words on space, reverse the order, put back together.
var j = $('li.time > a');
var t = j.text();
var a = t.split(' ');
var r = a.reverse();
j.text(r.join(' '));
This could have some nasty consequences in a multilingual situation.
Old school JavaScript:
function replaceLinkText(className, newContents) {
var items = document.getElementsByTagName('LI');
for (var i=0; i<items.length; i++) {
if (items[i].className == className) {
var a = items[i].getElementsByTagName('A');
if (a[0]) a[0].innerHTML = newContents;
}
}
}
replaceLinkText("time", "Review Time");
Note that modern browsers support getElementsByClassName(), which could simplify things a bit.
You can traverse the DOM and modify the Text with the following JavaScript:
var li = document.getElementsByClassName('time');
for (var i = 0; i < li.length; i++) {
li[i].getElementsByTagName('a')[0].innerText = 'new text';
}
Demo: http://jsfiddle.net/KFA58/

Categories