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>
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 the HTML as follows. what i need is when someone clicks on the span element i want to find its parents parent element check some conditions. i used prev() method but it gives me only the near parent(parent2 here)
<div class="container">
<div class="contain">
<div id="parent1">
<div class="parent2">
<span> Click here</span>
</div>
</div>
</div>
</div>
var currentComponent = $(event.target).prev(); //here i get parent2
How can i find the parents parent element(in this case parent2). i am not very familiar with jquery so any help would be appreciated.
You can try .closest.
From the docs:
the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements.
(...)
get the first element that matches the selector by testing the element itself and .
It traverses up through the element ancestors in the DOM and returns the first one that matches the selector you passed as an argument. So, in your example, you can do something like that:
$("span").on("click", function(e) {
var myParent = $(this).closest(".parent2");
var parentOfMyParent = $(this).closest(".parent1");
var contain = $(this).closest(".contain");
var containerAbove = $(this).closest(".container");
});
What you need is
var currentComponent = $(event.target).parent().parent()
To do it in a single call, you can use
var currentComponent = $(event.target).closest(".parent1")
Fiddle:
https://jsfiddle.net/c624re4o/
Code:
var grandParent = $(this).parent().parent();
Full Working Code
$(document).ready(function () {
$("span").click(function () {
var grandParent = $(this).parent().parent();
alert(grandParent.attr('id')); // Just for Testing
});
});
$(document).ready(function () {
$("span").click(function () {
var grandParent = $(this).parent().parent();
alert(grandParent.attr('id')); // Just for Testing
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="contain">
<div id="parent1">
<div class="parent2">
<span> Click here</span>
</div>
</div>
</div>
</div>
you can use .closest() or .parents() function with selector like .parents('#elementid')
Consider this HTML code:
<div id="container">
<div class="c1">Text1
<p class="pc1">Paragraph1</p>
</div>
<div class="c1">Text2
<p class="pc1">Paragraph2</p>
</div>
</div>
And here's Script I'm trying:
<script>
$(document).ready(function(){
$("#container").click(function(e){
var a=e.target.children().text();
//I want to store the text in the paragraph (e.g. Paragraph 1, when I click the first div) in var a.
var b=e.target.childNodes[0].nodeValue;
//I want to store the text in the div (e.g. Text1, when I click the first div) in var b.
});
});
</script>
But it's not working. I know I've written something wrong. What is the correct way to access those texts using event.target property?
The problem with e.target is it could be either the c1 element or the pc1 element.
You can target the c1 element with the click event and then find the first child of the c1 and its value
$(document).ready(function() {
$("#container").on('click', '.c1', function(e) {
var text = this.firstChild.nodeValue.trim();
snippet.log(text);
});
//using a gloabl handler, they way you have used
$("#container").click(function(e) {
var text = $(e.target).closest('div').contents().first().text();
snippet.log('2: ' + text);
});
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="c1">Text1
<p class="pc1">Paragraph1</p>
</div>
<div class="c1">Text2
<p class="pc1">Paragraph2</p>
</div>
</div>
$(document).ready(function() {
$("#container").click(function(e) {
var a = $(e.target).children().text();
//I want to store the text in the paragraph (e.g. Paragraph 1, when I click the first div) in var a.
alert(a)
//I want to store the text in the div (e.g. Text1, when I click the first div) in var b.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="c1">Text1
<p class="pc1">Paragraph1</p>
</div>
<div class="c1">Text2
<p class="pc1">Paragraph2</p>
</div>
</div>
Add $() to make it jquery object then you can use .children()
Since you are after the e.target's text node as well as the nested <p>, using jQuery .contents() filter would be a better option.
$("#container").children().click(function(e) { // limit events to children of #container
var selectElm = $(e.target);
var a,b;
selectElm.contents().filter( function(index,node){ // filter through the contents of selected elm
if(index === 0 ){ // only takes values of the first node (text only)
selectElm.is('p') ? a = $(this).text() : b = $(this).text() ; // assign a and b vars
}
});
});
See Demo
...and the shorter version w/o using .contents(),
$("#container").children().click(function(e) { // limit events to children of #container
var a,b;
$(e.target).is('p') ? a = e.target.childNodes[0].nodeValue : b = e.target.childNodes[0].nodeValue ;
});
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>
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.