I need to create a function which gets user input (a css selector) and removes all of those elements.
This is the function so far
function removeBySelector(selector) {
var thisOne = document.querySelectorAll(selector);
for(var i = 0; i<thisOne.length; i++) {
document.removeChild(thisOne[0]);
};
};
and the HTML that starts it
<button type="button" name="button" onclick="removeBySelector(prompt('Type the selector e.g p/ p.pClass'));">Remove By Selector</button>
change your method to
function removeBySelector(selector)
{
var thisOne = document.querySelectorAll(selector);
for(var i = 0; i<thisOne.length; i++)
{
thisOne[i].parentNode.removeChild( thisOne[i] ); //changed parentElement to parentNode
};
}
i'd advise using the framework jQuery! It is a very powerful tool that helps you simplify and improve your JavaScript code and it's performance.
With jQuery you can easily use this piece of code to remove any elements by CSS selector.
// Use any CSS Selector here
var elements = $(".class");
$.each(elements, function(){
$(this).remove();
)};
This keeps your code very easy to read and has a high performance.
//Try this code:
var removeElement=function(selector){
$(document).find(selector).remove();
};
removeElement('h1'); // will remove all H1 elements from Document.
You can do the same, without using any library with pure javascript (ES6 syntax in this case):
let elements = document.querySelectorAll(".please-remove");
elements.forEach(e => e.remove());
<div>
<div class="keep">Keep this element</div>
<div class="please-remove">1</div>
<div class="please-remove">2</div>
<div class="please-remove">3</div>
<div class="please-remove">4</div>
<div class="please-remove">5</div>
<div class="please-remove">6</div>
</div>
Related
I want to loop through a nested HTML DOM node, as shown below:
<div id="main">
<div class="nested-div-one">
<div class="nested-div-two">
<div class="nested-div-three">
</div>
</div>
</div>
<div class="nested-div-one">
<div class="nested-div-two">
<div class="nested-div-three">
</div>
</div>
</div>
</div>
How would I do this using Javascript to loop through every single one of the dividers?
I am guessing OP was not specific for DIV elements, here's a more dynamic approach:
So first you wanna get the first container, in your case it's:
var mainEl = document.getElementById('main');
Once you have that, each DOM element has a .children property with all child nodes. Since DOM is a tree object, you can also add a flag to achieve recursive behavior.
function visitChildren(el, visitor, recursive) {
for(var i = 0; i < el.children.length; i++) {
visitor(children[i]);
if(recursive)
visitChildren(children[i], visitor, recursive);
}
}
And now, let's say you want to change all div backgrounds to red:
visitChildren(mainEl, function(el) { el.style.background = 'red' });
You can use vanilla javascript for this
document.querySelectorAll('div').forEach(el => {
// el = div element
console.log(el);
});
I have HTML:
<footer class="footer">
<div class="container-fluid wrapper">
...
</div>
</footer>
How do I remove the whole footer markup using javascript (no jQuery available)?
I've tried:
var elem = document.getElementsByName("footer");
elem.remove();
...and a couple of other variations, but I can't get it to delete.
Any ideas?
Thanks, Mark
Yes, you can do like this
function removeTagByTagName(tagName) {
var ele = document.getElementsByTagName(tagName);
return ele[0].parentNode.removeChild(ele[0]);
}
function removeTag(tag) {
var ele = document.getElementsByTagName(tag);
return ele[0].parentNode.removeChild(ele[0]);
}
var btn = document.getElementById("delet");
btn.addEventListener("click", function(){
removeTagByTagName("footer");
});
<body>
<button id="delet">Delete Footer!</button>
<footer class="footer" name="footer">
<div class="container-fluid wrapper">
blab bal babla
</div>
</footer>
</body>
you cannot use .remove with all browsers, since the support is not that good yet. I would recommend polyfilling the remove, so that you can use this. Use the following polyfill (taken from MDN):
// from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('remove')) {
return;
}
Object.defineProperty(item, 'remove', {
configurable: true,
enumerable: true,
writable: true,
value: function remove() {
this.parentNode.removeChild(this);
}
});
});
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
Now you can use .remove() with ease.
You can also use .removeChild() if you know the parent of the node you want to delete. Something like this:
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
So since your is inside the , you can treat the body as the parent and remove its child () using similar code as above snippet.
You would need to grab that specific footer element. What you have with var elem = document.getElementsByName("footer"); grabs a collection of all elements named "footer" but if you want to do it that way, you need to add the name="footer" attribute to your footer element. The way your HTML is set up right now, you could change that line to:
var elem = document.getElementsByTagName("footer");
If you only have one footer element, then you can target that one like this:
var elem = document.getElementsByTagName("footer")[0];
Otherwise, you could assign that element an ID, or figure out which footer item in the collection it was (i.e. document.getElementsByTagName("footer")[3]).
Once you have that specific element, you can remove it like this:
elem.parentNode.removeChild(elem);
The removeChild function and querySelector can be used to fulfil your needs.
function remove(){
var el=document.querySelector('footer.footer');
el.parentNode.removeChild(el);
}
remove();
<footer class="footer">
<div class="container-fluid wrapper">
...
</div>
</footer>
I would like to remove the parent without removing the child - is this possible?
HTML structure:
<div class="wrapper">
<img src"">
</div>
<div class="button">Remove wrapper</div>
After clicking on the button I would like to have:
<img src"">
<div class="button">Remove wrapper</div>
Pure JS (ES2015) solution, in my opinion easier to read than jQuery-solutions.
node.replaceWith(...node.childNodes)
Node has to be an ElementNode
const wrapperNode = document.querySelector('h1')
wrapperNode.replaceWith(...wrapperNode.childNodes)
<h1>
<a>1</a>
<b>2</b>
<em>3</em>
</h1>
Pure JS solution that doesn't use innerHTML:
function unwrap(wrapper) {
// place childNodes in document fragment
var docFrag = document.createDocumentFragment();
while (wrapper.firstChild) {
var child = wrapper.removeChild(wrapper.firstChild);
docFrag.appendChild(child);
}
// replace wrapper with document fragment
wrapper.parentNode.replaceChild(docFrag, wrapper);
}
Try it:
unwrap(document.querySelector('.wrapper'));
Surprised that nobody's posting the simplest answer:
// Find your wrapper HTMLElement
var wrapper = document.querySelector('.wrapper');
// Replace the whole wrapper with its own contents
wrapper.outerHTML = wrapper.innerHTML;
Could use this API: http://api.jquery.com/unwrap/
Demo http://jsfiddle.net/7GrbM/
.unwrap
Code will look something on these lines:
Sample Code
$('.button').click(function(){
$('.wrapper img').unwrap();
});
Pure javascript solution, i'm sure someone can simplify it more but this is an alternative for pure javascript guys.
HTML
<div class="button" onclick="unwrap(this)">Remove wrapper</div>
Javascript (pure)
function unwrap(i) {
var wrapper = i.parentNode.getElementsByClassName('wrapper')[0];
// return if wrapper already been unwrapped
if (typeof wrapper === 'undefined') return false;
// remmove the wrapper from img
i.parentNode.innerHTML = wrapper.innerHTML + i.outerHTML;
return true;
}
JSFIDDLE
if you're using jQuery:
$(".wrapper").replaceWith($(".wrapper").html());
If the wrapper element contains text, the text remains with child nodes.
I need to hide all the elements that have the string "replies-36965584" anywhere in their IDs.
HTML:
<div id="replies-36965584_1">aaaa</div>
<div id="replies-36965584_2">aaaa</div>
<div id="replies-36965584_3">aaaa</div>
<div id="replies-36965584_4">aaaa</div>
<div id="replies-36222224_2">nnnn</div>
JavaScript:
document.getElementById("replies-36965584").style.display="none"
How can I modify this JS to select the first four elements?
You can do this with CSS and attribute selectors.
[att^=val]
Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.
Source: http://www.w3.org/TR/css3-selectors/#attribute-substrings
jsfiddle
CSS
[id^="replies-36965584_"] {
display: none;
}
Is using jQuery an option? If so, this is dead simple:
$(document).ready(function(){
$('div[id^="replies-36965584"]').hide();
});
If you're unfamiliar with jQuery, here's a link to get started: http://learn.jquery.com/javascript-101/getting-started/
EDIT: Fixed syntax error.
EDIT: Added jsFiddle: http://jsfiddle.net/xbVp9/
If you don't know certain literal values but you know the general pattern and only the number will change, then I will consider some matching with regular expresiion.
You can do it the painful way:
var o = document.getElementsByTagName("div");
for (var i=0;i<o.length;i++) {
if(o[i].id.indexOf('replies-36965584') == 0) {
o[i].style.display = 'none';
}
}
The only way to do this with vanilla javascript that I know of, is to fetch all the divs on the page, and test the id's for the ones you want.
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; ++i) {
var div = divs[i];
if (/replies-36965584/.test(div.id)) {
div.style.display = 'none';
}
}
I need to read elements class name. I have elements like this:
<article class="active clrone moreclass">Article x</article>
<article class="active clrtwo moreclass">Article y</article>
<article class="active clrthree moreclass moreclass">Article z</article>
<article class="active clrone moreclass">Article xyza</article>
I need to parse out class name that starts with clr. So if second element was clicked then I would need to get clrtwo className.
You can use a regular expression match on the class name of the clicked item to find the class that begins with "clr" like this:
$("article").click(function() {
var matches = this.className.match(/\bclr[^\s]+\b/);
if (matches) {
// matches[0] is clrone or clrtwo, etc...
}
});
Here is solution for you:
$('article').click(function () {
var className = this.className.split(' ');
for (var i = 0; i < className.length; i+=1) {
if (className[i].indexOf('clr') >= 0) {
alert(className[i]);
}
}
});
http://jsfiddle.net/vJfT7/
There's no matter how you're going to order the different classes. The code will alert you a class name only of there's 'clr' as a substring in it.
Best regards.
If you don't need to find elements based on these classes (e.g. doing $('.clrtwo')) it would be nicer to store the data as a data-clr attribute. This is standards-compliant from HTML5, and is supported by jQuery using the .data() function.
In this instance, I would modify your HTML in this way:
<article class="active moreclass" data-clr="one">Article x</article>
<article class="active moreclass" data-clr="two">Article y</article>
<article class="active moreclass moreclass" data-clr="three">Article z</article>
<article class="active moreclass" data-clr="one">Article xyza</article>
I would then use Javascript like this:
$('article.active').click(function() {
console.log($(this).data('clr'));
});
jsFiddle example
If it is always the second class name which is of interest you can do this:
$("article").click(function () {
// split on the space and output the second element
// in the resulting array
console.log($(this)[0].className.split(" ")[1]);
});
http://jsfiddle.net/karim79/Z3qhW/
<script type="text/javascript">
jQuery(document).ready(function(){
$("article").click(function(){
alert($(this).attr('class').match(/\bclr[^\s]+\b/)[0]);
});
});
</script>
This should jquery script should do what you asked (tested on jsfiddle):
$(document).ready(function () {
function getClrClass(elem) {
var classes = elem.getAttribute('class').split(' ');
var i = 0;
var cssClass = '';
for (i = 0; i < classes.length; i += 1) {
if (classes[i].indexOf('clr') === 0) {
cssClass = classes[i];
i = classes.length; //exit for loop
}
}
return cssClass;
};
$('article').click(function (e) {
var cssClass = getClrClass($(this)[0]);
alert(cssClass);
e.preventDefault();
return false;
});
});
Hope this helps.
Pete
Use an attribute selector to get those that have class names that contain clr.
From there:
extract the class name (string functions)
analyze the position
determine the next element
The latter two might be best served by a translation array if you only had a few classes.
UPDATE
I agree with lonesomeday, you'd be far better off using data-* attribute to handle such logic. Using CSS as JavaScript hooks is a thing of the past.
http://jsfiddle.net/4KwWn/
$('article[class*=clr]').click(function() {
var token = $(this).attr('class'),
position = token.indexOf('clr');
token = token.substring(position, token.indexOf(' ', position));
alert(token);
});