I was wondering, say I have the following DOM structure in my View / Webpage
<div>
<p>I am some text or a comment or something</p>
X
</div>
<div>
<p>I am some text but this Div may have more content like IMG or inputs</p>
X
</div>
I'd like to add a method on the controller called deleteThisDiv that will remove the parent DIV of the href and all the DIV's contents (including the href I just clicked). This is easy with jQuery as I could just get the parent and use $target.remove() however I want to get out of the jQuery way of things and remove the item using AngularJS best practice. I know I could use jqLite as $target.remove() is supported and I guess I could climb the DOM tree to find the DIV but is there a better* way to do this (like using ng-show/ng-hide, etc)? Please note that I can add IDs to my HTML but I don't want to populate the HTML structure with IDs just yet.
When I say better I mean an AngularJS way! I just want to get out of the mind set of using jQuery for these things... please note that the HTML is coded and not produced by an array or looping through objects, etc
I believe the "angular way" would be to have the divs show conditionally using the ng-show directive if what you're looking for is a function that can show/hide the div. If you're looking to literally either have one or the other div in the DOM I'd take a look at ng-if or ng-switch.
Note that ng-if and ng-switch only evaluates once meaning you wouldn't be able to have a function that "removed" a DIV. ng-show on the other hand is evaluated on each $digest cycle
<div ng-show="someExpression>
<p>I am some text or a comment or something</p>
X
<!--Clicking this will show/hide the div-->
</div>
<div ng-if="someExpression">
<p>I am some text but this Div may have more content like IMG or inputs</p>
X
<!--Clicking this has no effect because ng-if is only evaluated once-->
</div>
Use ng-show...
<div ng-show="showFlag">
<p>I am some text or a comment or something</p>
X
</div>
in your controller you'll need to define the variable like:
$scope.showFlag= true;
You might be looking for this one.
module.controller('TestController',
function TestController($scope) {
$scope.deleteThisDiv = function ($event) {
$event.target.parentNode.parentNode.removeChild($event.target.parentNode);
};
});
I use this directive for very similar reasons:
<div destroyOnEvent="destroyThisDiv">
<p>I am some text or a comment or something</p>
X
</div>
.directive('destroyOnEvent',function($rootScope) {
return {
restrict : 'A',
link : function($scope,$element,$attrs) {
$rootScope.$on($attrs.destroyOnEvent,function() {
$element.remove();
});
}
}
});
Related
which option among the following is better or used as a standard way to show/hide the html elements
changing element.style.display
adding/removing a separate class called hide {display: none}
any other standard way
PS: this JavaScript hide/show element question uses the first option mentioned( changes the style to block to show which may not be desired). I would like to know whether this method is used in most websites or the adding /removing a separate class or any other way
A third way in the answers below https://stackoverflow.com/a/68983509/14478972
I prefer to toggle a class using DOMTokenList.toggle():
The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.
Well except the first and second, there is the other way.
Which is rendering the element its self.
It has a better security. as the user wont know if there is a hidden element inside the toggle div. Eg when people try to look at the html
Have a look below
I used jQuery as its easier to write. If you are not able to rewrite a JavaScript version will be happy to rewrite for you.
var items = $(".toggle");
var item = {};
// setup the auto toggle
$(".toggle").each(function(el) {
var id = new Date().getUTCMilliseconds() + $(this).index()
item[id] = $(this).find("content")
if (!$(this).hasClass("show")){
$(this).find("content").remove();
}
$(this).attr("id", id)
});
$(".toggle").click(function() {
if ($(this).find("content").length > 0)
$(this).find("content").remove();
else $(this).append(item[$(this).attr("id")])
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle">
<h1>click here to toggle content </h1>
<content>
this is a test
</content>
</div>
<div class="toggle show">
<h1>click here to toggle content(start state is visible) </h1>
<content>
this is a test
</content>
</div>
Option 1 would be standard for only hiding the element, but if you would like to add other styles like transitions and pointer events option 2 is preferred
I have three divs. How should I append a div onto an unknown div?
<div class="main" >
<div id="drag-box" >
<div id="" class=""> </div>
</div>
</div>
I want to append div on an unknown div which is come after drag-box div. I don't know which div comes after drag-box div. But there must be one div after drag-box div.
$("#drag-box div:first-child").append("<span />");
or
$("#drag-box div").first().prepend("<span>first</span>");
For a complete answers, here it is working:
http://jsfiddle.net/dMUD3/
try this
$("#drag-box div:first-child").attr("id");
Instead of giving you a one liner I would like to give you an indepth solution.
A browser takes your html and parses what is called a DOM Tree out of it.
so if your html is .
<div class="a">
<div class="foo"></div>
<button class="foogle"></button>
</div>
The tree structure will become something like
`-div.a
|-div.foo
`Button.foogle
You should actually look into DOM Api's at MDN
How DOM helps ?
With DOM api's you can actually access the unknown div using the reference to a known div. So if you actually understand your markup and its representation in DOM it should be pretty simple to get reference to nth child of an element;
You can access the child elements by the children attribute.
So
// Get reference to the element.
var parent = document.getElementById("drag-box");
// Use the dom.
var child_i_want = parent.children[0];
// or there is another way
var child_i_reallyWant = parent.firstElementChild;
There are solutions with jQuery but I feel its important for you to Understand basics of DOM even when there are helpful abstraction libraries in existance.
You'll need the + selector. It applies to the object directly following. See here.
.drag-box + div {
}
$('<div></div>').appendTo($('#drag-box div:first'))
I have a markup in one of my website pages as follows:
<div id="mainPage">
<div>
<div><ul><li>etc.</li></ul>
</div>
<div>
<div><ul><li>etc.</li></ul>
</div>
</div>
What the above means is that there's a main div in my website which has the content. I want to take all the children of the particular div and save it in a var, since I want to use that var later for something like $('resurrectPage').append(someVar); where someVar has the dom elements from the main page div.
How can all the children of a particular element be selected and added to a var?
$('#mainPage').html() would give you the entire thing in a string "<div>
<div><ul><li>etc.</li></ul> </div> <div> <div><ul><li>etc.</li></ul> </div>"
$('#mainPage').children() would give you immidiate children [div,div]
$('#mainPage').find('.div') would giv =e you all the divs inside it [div,div,div,div]
if #mainPage is your main div, you can get of it's children by
var someVar = $('#mainPage').children();
Official api page
I think you're looking for jQuery detach method...
http://api.jquery.com/detach/
It will remove an element and store its contents, ready to be re-appended:
var a = p = $("a").detach()
If you only need the HTML you can save the HTML: var someVar = $("#mainPage").html(); and then append the HTML with the code you already have. Please tell me if I have misunderstood your question.
I want to append some text after 2 closing divs to a sector element.
Click me
</div>
</div>
// this is where I want to append the text
My code appends the text after the link. How can I say "append it after the 2nd closing div"?
$('a.thingIClicked').click(function() {
$(this).append('hello');
});
The most direct way to do this is to find the second parent <div> element, and then insert the text after it.
$('a.thingIClicked').click(function() {
$(this).parent("div").parent("div").after("some text");
});
This will insert the text on the outside of the second <div> parent. Using append() will put the text on the inside of the parent, which from your example doesn't appear to be what you want.
There's probably a more elegant solution, but how about:
$('a.thingIClicked').click(function() {
$(this).parent().parent().after('hello');
});
Edit: #Zack is correct (and should probably get the answer credit for this one) - my original code would have added the text into the second enclosing div, rather than after it. I've edited my code above accordingly.
The easiest way would be to give the outer div an id and then use $("#outerdivid").
EDIT: Below will not work, but leaving it here for reference
However, you should also be able to use a jquery :parent filter:
http://api.jquery.com/filter/
$('a.thingIClicked').filter(':parent').filter(':parent').click(/**/);
Use .insertAfter()
http://api.jquery.com/insertAfter/
<div class="container">
<h2>Greetings</h2>
<div>Hello</div>
<div class="inner">Goodbye</div>
</div>
We can create content and insert it after several elements at once:
$('<p>Test</p>').insertAfter('.inner');
Use .insertAfter() - http://api.jquery.com/insertAfter/
<div class="container">
<h2>Greetings</h2>
<div>Hello</div>
<div class="inner">Goodbye</div>
</div>
We can create content and insert it after several elements at once:
$('<p>Test</p>').insertAfter('.inner');
Hi guys lets say I have the following html:
<div class="owner">
<div>
click
</div>
</div>
<div class="owner">
<div>
click
</div>
</div>
I want to put code in the onclick handler so it results in selecting the element of class 'owner' which encloses it - so I don't have to refer to the parent element by typing in this.parentNode.parentNode etc
I'd appreciate if theres a way to do it using selectors from both prototype and jquery.
$().parents(<selector>) is your friend
$(a).click(function() {
$(this).parents(".owner").css("background-color", "yellow");
})
example
Why not use this.parentNode.parentNode? If the structure is fixed, this will be faster and more efficient.
If the structure is not fixed, a jQuery way would be something like:
$(this).parentsUntil (".owner").filter (".owner");