<div> tag to <img> tag Javascript - javascript

Hello is it possible to change div tags to image tags?
I tried using this
var testDivTags= document.getElementsByClassName('div_tags');
var testImgTag= document.createElement("img");
for (var i = 0; i < testDivTags.length; ++i) {
testDivTags[i].parentNode.replaceChild(testImgTag, testDivTags[i])
}
But it doesn't work. Any ideas?

The problem is that an element can't be at different places in the DOM simultaneously.
Instead, you should clone the element, and insert the clones:
parent.replaceChild(newChild.cloneNode(), oldChild)
Moreover, there is another problem: the HTMLCollection returned by getElementsByClassName is live. Therefore, when you replace the elements, they disappear from the list, and following ones are reindexed to lower indices. To fix that, you can
Iterate the live HTMLCollection collection backwards:
var liveC = document.getElementsByClassName('div_tags');
for (var i = liveC.length-1; i >= 0; --i)
liveC[i].parentNode.replaceChild(testImgTag.cloneNode(), liveC[i]);
Convert it to an array:
var array = [].slice.call(document.getElementsByClassName('div_tags'));
for (var i = 0; i < array.length; ++i)
array[i].parentNode.replaceChild(testImgTag.cloneNode(), array[i]);
Use querySelectorAll, which returns a static NodeList collection:
var staticC = document.querySelectorAll('.div_tags');
for (var i = 0; i < staticC.length; ++i)
staticC[i].parentNode.replaceChild(testImgTag.cloneNode(), staticC[i]);

Related

How to remove all elements except last one with same document.querySelectorAll(".someClass") using only javascript without jQuery

My query is simple :
How to remove all elements except last one with same document.querySelectorAll(".someClass") using only javascript without jQuery.
I can do it with jQuery with only one line like this:
$('.someClass').not(':last(2)').remove();
But I want to do it with pure JavaScript; how can I do that?
Any idea?
I tried this code :
var lists = document.querySelectorAll(".someClass");
for(var i = 1; i < lists.length; i++) {
lists[i].parentElement.removeChild(lists[i]);
}
But it removes all elements except the first one. But I want to keep the last one.
This will remove all but the last element from your nodeList
EDIT:
const elems = Array.from(document.querySelectorAll(".someClass"))
elems.pop()
elems.map(node => node.parentNode.removeChild(node))
var lists = document.querySelectorAll(".someClass");
for(var i = 0; i < lists.length -1; i++) {
lists[i].parentElement.removeChild(lists[i]);
}
Try using this.
var lists = document.querySelectorAll(".someClass");
for(var i = 1; i < lists.length; i++) {
if (i !== lists.length - 1) lists[i].parentElement.removeChild(lists[i]);
}
You can perform the above action on every item in the array except for the last one (the last index is array.length - 1 since the first index is 0.
You were close:
let endIndex = 1 // how many you want to delete
var lists = document.querySelectorAll(".someClass");
for(var i = 0; i < lists.length - 1 - endIndex; i++) {
lists[i].parentElement.removeChild(lists[i]);
}
Stop just before the last one:
var lists = document.querySelectorAll(".someClass");
for(var i = 1; i < lists.length - 1; i++) {
// ^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
lists[i].parentElement.removeChild(lists[i]);
}
Or alternatively, in all vaguely-modern browsers:
const lists = Array.prototype.slice.call(
document.querySelectorAll(".someClass"),
0, -1
);
for (const list of lists) {
list.remove();
}
That uses the slice method from Array.prototype to grab all of the entries from the NodeList returned by querySelectorAll except the last one, then loops over that result removing those elements.
Try with this:
$("#parent_id").children(":not(#id_n)").remove();

How to replace .each() with for loop in javascript [duplicate]

This question already has answers here:
$.each() vs for() loop - and performance
(6 answers)
Closed 5 years ago.
I want to replace my
$("p").each(function(i)
with
for (var i = 0, len = $('p').length; i < len; i++) {
$('p')[i];
}
for faster performance. I want to keep the same switch statement. How do i do it? I'm new with javascript and also my switch statement is alot longer , but i shorten it so you guys can see it better. My problem is $(this) . Thanks in advance.
for (var i = 0, len = $("p").length; i < len; i++) {
$("p")[i];
}
$("p").each(function(i) {
switch(window.localStorage['kgenfavred' + i])
{
case 'yred':
$(this).addClass("favoritesred");
$(this).removeClass("favoritesyellow");
break;
}
});
var paragraphs = document.getElementsByTagName('p');
for (var p = 0; p < paragraphs.length; p++) {
switch(window.localStorage['kgenfavred' + p]) {
case 'yred':
paragraphs[p].classList.add('favoritesred');
paragraphs[p].classList.remove('favoritesyellow');
break;
}
}
JSFiddle example
Your current approach is likely to be slower, since you've added a DOM lookup on each iteration. If you really want to convert to a for loop, capture your element set first, then iterate over it - accessing the current element with .eq(index):
var $p = $('p');
for (var i = 0, len = $p.length; i < len; i++) {
// get jquery element
console.log($p.eq(i));
// or get DOM node
console.log($p.get(i));
}
As #Kinduser pointed out, it probably would be fastest/easiest just to cut jQuery out of the picture altogether:
var p = document.querySelectorAll('p');
for (var i = 0; i < p.length; i++) {
console.log(p[i]);
}
Or newer:
document.querySelectorAll('p').forEach((element) => {
console.log(element);
});
This would be incorrect. You can use .each() method of jQuery:
var $ps = $(document).find('p');
for (var i=0; i<$ps.length; i++)
{
let temp = $ps[i]; /// this is a dom element and if you want use jQuery methods, you need to use a selector over it;
let $temp = $(temp); /// this is jQuery element
/// Do whatever you want here
}

Get XML node with specified type in JS

Is there any built in function in JavaScript to get only element nodes, or do I have to add another loop which counts the actual number of those if I need it before, like:
l = 0;
for(i = 0; i < x.childNodes.length; i++){
if(x.childNodes[i].nodeType = 1) l++;
}
for(i = 0; i < x.childNodes.length; i++){
if(x.childNodes[i].nodeType != 1) continue;
new Something(l);
}
Node.children is a read-only property that returns a live
HTMLCollection of the child elements of Node.
Syntax
var elList = elementNodeReference.children;
elList is a HTMLCollection, which is an ordered collection of DOM
elements that are children of elementNodeReference. If there are no
element children, then elList contains no elements and has a length of
0.

Two different types of NodeLists? Cannot set properties on one NodeList to Array

These two examples are both node lists, but only the first works.
Works as expected:
var apple = document.getElementById('apple');
var nodeList = document.getElementsByTagName('li'); // Line of concern
var array = [];
for(var i = 0; i < nodeList.length; i++) {
array[i] = nodeList[i];
}
for(var i = 0; i < array.length; i++) {
array[i].style.display = 'none';
}
Does not work (error is: "Uncaught TypeError: Cannot set property 'display' of undefined"):
var apple = document.getElementById('apple');
var nodeList = apple.parentNode.childNodes; // Line of concern
var array = [];
for(var i = 0; i < nodeList.length; i++) {
array[i] = nodeList[i];
}
for(var i = 0; i < array.length; i++) {
array[i].style.display = 'none';
}
So if both variables "nodeList" are actual node lists, then why can't I set the properties on the latter example, nor anything similar.
Also, how do I solve the issue on the latter?
No jQuery please for this question.
Thank you.
There are not two different types of NodeLists.
apple.parentNode.childNodes
returns a NodeList, but it contains ALL the nodes--including new line & space characters between elements on the HTML. So the reason I couldn't apply the properties I wanted was because some of the nodes were non-elements.
The answer then in place of that, is to use the element-only selecting methods; in this case: parentElement & children:
apple.parentElement.children
See Mozilla's Developer page on nodes, as well as the left-hand column for more node methods.

Remove elements whose id name contains certain string

I want to remove all elements (suppose they're all divs) whose id name contains the string bs. How to do this via javascript regardless of they are nested elements or not? (not jquery)
<div id="new_bs_add"></div>
<div id="bsremove"></div>
<div id="somethingelse"></div>
... and many more
No jQuery, but if there's support for CSS3 selectors you can go for
var rem = document.querySelectorAll("[id*='bs']"), i = 0;
for (; i < rem.length; i++)
rem[i].parentNode.removeChild(rem[i]);
Otherwise, just go for this slight edit of VisioN's solution:
var divs = document.querySelectorAll("[id]");
for (var i = 0, len = divs.length; i < len; i++) {
var div = divs[i];
if (div.id.indexOf("bs") > -1) {
div.parentNode.removeChild(div);
}
}
Pure JavaScript:
var divs = document.getElementsByTagName("div");
for (var i = divs.length; i;) {
var div = divs[--i];
if (div.id.indexOf("bs") > -1) {
div.parentNode.removeChild(div);
}
}
As an example, in jQuery it is one line:
$("div[id*='bs']").remove();
DEMO: http://jsfiddle.net/c4ewU/
The most portable method to obtain a list of elements is document.getElementsByTagName. However the resulting list is a live node list which means that if you modify the document, the list changes too!
There are two solutions for this. One is to take a copy of the list:
var nodes = document.getElementsByTagName('div');
var copy = [].slice.call(nodes, 0); // take a copy
for (var i = 0, n = copy.length; i < n; ++i) {
var d = copy[i];
if (d.parentNode && d.id.indexOf('bs') >= 0) {
d.parentNode.removeChild(d);
}
}
The second is to either work through the list backwards, or ensure that you don't advance the iterator if you modify the list. This takes the latter approach:
var nodes = document.getElementsByTagName('div');
for (var i = 0; i < nodes.length; /* blank */ ) {
var d = nodes[i];
if (d.id.indexOf('bs') >= 0) {
d.parentNode.removeChild(d);
} else {
++i; // iterate forward
}
}
try this code
first get all elements contain certain text (here 'bs')
var matches = [];
var searchElements = document.getElementsByTagName("body")[0].children;
for(var i = 0; i < searchElements.length; i++) {
if(searchElements[i].tagName == 'DIV') {
if(searchElements[i].id.indexOf('bs') != -1) {
matches.push(searchElements[i]);
}
}
}
Then delete them from body of html
for(var i = 0;i<matches.length; i++)
matches[i].parentNode.removeChild(matches[i]);
If you remove them in the first loop, there will be some tags will not deleted as the children array length is decreased each time you delete a node. So the better way to get them all in an external array and then delete them.

Categories

Resources