I think the title is clear, but I've some examples for you guys, here is my idea:
I've this Html5:
<html>
<head></head>
<body class="oldParent">
<div class="p1"></div>
<div class="p2"></div>
<div class="p3"></div>
<div class="p4"></div>
<div class="p5"></div>
<div class="NewParent"></div>
</body>
</html>
as you can see my NewParent is child of My OldParent
(i want to move all body elements except NewParent), and i need to move all elements except this one:
<div class="**NewParent**"></div>
I'm New to Javascript and I thought that you guys know how to add exception
for this, I've found this too:
var newParent = document.getElementById('NewParent');
var oldParent = document.getElementById('OldParent');
while (oldParent.childNodes.length > 0) {
newParent.appendChild(oldParent.childNodes[0]);
}
but i don't know how to add exception!?
I need help:(
You're pretty close with your original code. Just switch to getElementsByClassName - but be aware it returns a collection so you'll have to index into it. You might want to switch to id's if that's an option.
Then you can basically just add an if condition to test for the className of the element to exclude:
var newParent = document.getElementsByClassName('NewParent')[0];
var oldParent = document.getElementsByClassName('oldParent')[0];
while (oldParent.childNodes.length > 0) {
if (oldParent.childNodes[0].className !== 'NewParent') {
newParent.appendChild(oldParent.childNodes[0]);
}
else { break; }
}
Here's a jsfiddle you can play with. Be careful with your class names, the ones for old and new parents have different casing.
I would add while this is closest to your original code, it may not actually be the best way to solve this. This assumes your new parent is the last in the collection as it has to break out of your while loop due to the way you're looping. Cloning as the other answer shows is probably a safer solution.
You can try below method.
Get your current element which you want to retain.
Create a Clone of that element.
Empty the entire parent element.
Append the element which you have cloned earlier.
var newParent = document.getElementsByClassName('NewParent')[0];
var cln = newParent.cloneNode(true);
document.getElementsByClassName('oldParent')[0].innerHTML = '';
document.getElementsByClassName('oldParent')[0].appendChild(cln);
<html>
<head></head>
<body class="oldParent">
<div class="p1">1</div>
<div class="p2">2</div>
<div class="p3">3</div>
<div class="p4"5></div>
<div class="p5">5</div>
<div class="NewParent">77</div>
</body>
</html>
I have the following code:
.recipe
.ingredients
= f.simple_fields_for :ingredients do |ingredient|
= render 'ingredient_fields', f: ingredient
.row#links
.col-xs-12
= link_to_add_association "", f, :ingredients
%hr
I need to select the ingredients div using jquery in the format of $("#links")["closest"](".recipe > .ingredients") but this doesn't select anything.
It's frustrating though as $("#links")["closest"](".recipe > .row") will return the correct div.
Fiddle of what works and what I want: https://jsfiddle.net/yL6dr4s1/
According to jQuery documentation, closest method tries to find element matching the selector by testing the element itself and
traversing up through DOM.
It does not go through siblings of the element.
Based on your requirements, it seems like you want to traverse the tree for getting match in siblings. jQuery has siblings method to do that. So one solution would be to use siblings method like:
$("#links")["siblings"](".recipe > .ingredients")
Another soultion would be to get closest parent and then use children as answered by #mhodges
As for the query $("#links")["closest"](".recipe > .row"):
It works fine because closest method finds the match in the element itself.
Here is the example to showcase that:
$(document).ready(function() {
// Match found because it is parent
console.log($("#links")["closest"](".wrapper").length);
// No match found because element is sibling
console.log($("#links")["closest"](".row1").length);
// No match found because element is sibling
console.log($("#links")["closest"](".row3").length);
// Match found because it is element itself
console.log($("#links")["closest"](".row2").length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="row1">
<span>Content1</span>
</div>
<div class="row2" id="links">
<span>Content2</span>
</div>
<div class="row3">
<span>Content3</span>
</div>
</div>
I am not sure of your requirements on using the exact selector/syntax you provided, but this selector works exactly how you want it to.
$(this).closest(".recipe").children(".ingredients").append('<br/><input type="text" value="Flour">');
Edit
This is the closest I could get:
$(this)["closest"](".recipe").children(".ingredients").append('<br/><input type="text" value="Flour">');
I don't think you can use the selectors in the way you propose.
As far as the DOM is concerned (and jQuery), the element defined by ingredient and the element defined by row are not related. You have to traverse up to the parent element, then back down to get to the child.
Here is a fiddle that hopefully demonstrates the issue.
If you can change it so that ingredient and row are both within the same parent div, you might have more luck with your test selector syntax.
When jQuery gets to buggy, doesn't have a certain option or just becomes to messy to use for a certain operation, it is good we also have access to good old plain javascript.
document.querySelector('#addToIngredients').addEventListener('click' , function(e) {
var recipe = getClosest(e.target,'recipe');
if (recipe) {
var ingred = recipe.querySelector('.ingredients');
ingred.innerHTML += '<br/><input type="text" value="Flour">';
}
});
function getClosest(elem,cls) {
var el = elem.parentNode;
while (el){
if (el.className.indexOf(cls) > -1) {
return el;
}
el = el.parentNode;
}
return false;
}
<div class="recipe">
<div class="ingredients">
<input type="text" value="Eggs"><br/>
<input type="text" value="Flour">
</div>
<div class="row">
<div class="col-xs-12">
Add to .ingredients
</div>
</div>
<hr/>
</div>
Of course they can be combined
$(function() {
$("#addToIngredients").on('click', function(e) {
var recipe = getClosest(e.target,'recipe');
if (recipe) {
var ingred = recipe.querySelector('.ingredients');
ingred.innerHTML += '<br/><input type="text" value="Flour">';
}
});
})
I am trying to select all following elements of an element I choose. They don't necessarily have to be direct siblings of my chosen Element, so .nextAll() won't work.
Here's an example:
<div class="scope">
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
<div> 4 </div>
</div>
NOT THIS
My element is a[href="2"], so I want to select a[href="3"] and a[href="4"], but not a[href="x"] because it's not in my scope.
I found this, but it only fetches one follower, but I need all of them.
I just wrote this, which works great, but it seems odd to me and I am sure that there have to be better solutions than this one:
var $two = $('a[href="2"]');
var selection = [];
var comes_after_2 = false;
$two.closest('.scope').find('a').each(function(){
console.log(this, $two.get(0));
if(comes_after_2){
selection.push(this);
}
if(this == $two.get(0)){
comes_after_2 = true;
}
});
$(selection).css('background', 'red');
Here is a Fiddle to test it: http://jsfiddle.net/mnff40fy/1/
Please feel free to modify it, if there's a better solution. Thank you!
var $all_a = $two.closest('.scope').find('a');
// Get the position of the selected element within the set
var a_index = $all_a.index($two);
// Select all the remaining elements in the set
var $followers = $all_a.slice(a_index+1);
$followers.css('background', 'red');
DEMO
How about this?
JSFiddle
I changed the markup a little to have the href='#' so you could click each one and see how the other elements respond.
$('a').click(function(){
$('a').css('background', 'none');
var scopeDiv = $(this).closest('div.scope');
var thisIndex = $(scopeDiv).find('a').index(this);
$(scopeDiv).find('a').not(this).each(function(index){
if(index >= thisIndex)
$(this).css('background', 'red');
});
});
As an alternative, you can use .nextAll() if you modify it a bit.
In your html code, you placed the a elements as children of the div tags. In order to incorporate .nextAll() you should select for the wrapper div elements and then call .nextAll() and then select for the children a elements.
Here is what I mean.
html
<div class="scope">
<div>
1
</div>
<!-- Start Here -->
<div class="start">
2
</div>
<div>
3
</div>
<div>
4
</div>
</div>
NOT THIS
js
$( '.start' ).nextAll().children( 'a' ).css( 'background-color', 'red' );
Explanation:
I select the wrapper div with $( '.start' )
I then select all of its subsequent siblings with .nextAll()
Of those siblings, I select their children that match 'a'
I apply the css
And here is the Fiddle
I want to get the position of a an element in its parent. For example
<div>
<h2 class="one">A</h2>
<span>Something</span>
<h2 class="two">B</h2>
<h2 class="three">C</h2>
</div>
Now suppose I get a reference of h2.two $('h2.two'); in an event. I want the position of this element relative to other h2's in the div. In this case it is 2. and please don't tell me I can get it through the classname, because there won't be these classnames. Its just for explanation.
NB: I want its position in the list of h2, basically in $('h2.two').parent().children('h2') not all elements
function buildPath(element)
{
var Xpath,position=-1;
element=$(element);//Just in case;
Xpath=getTagName(element);
parent=element.parent();
console.log(parent.children(Xpath));
var position = element.siblings(Xpath).element.index(element);//I want the position here
Xpath="/"+Xpath+"["+position+"]";
console.log(Xpath);
console.log(getTagName(parent));
if (getTagName(element)=='body')
return Xpath;
}
var $theH2 = $('h2.two');
var index = $theH2.siblings("h2").andSelf().index($theH2);
Here is a working example:
http://jsfiddle.net/Bm6Wd/
Click on an h2 and it will alert the index.
I just created script that shows/hides (toggles) block of HTML. There are four buttons that each can toggle its HTML block. When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button... it hides that HTML block and shows new one.
Here is what I have at the moment:
$('.btn_add_event').click( function() {
$('.block_link, .block_photos, .block_videos').hide();
$('.block_event').toggle();
});
$('.btn_add_link').click( function() {
$('.block_event, .block_photos, .block_videos').hide();
$('.block_link').toggle();
});
$('.btn_add_photos').click( function() {
$('.block_event, .block_link, .block_videos').hide();
$('.block_photos').toggle();
});
$('.btn_add_videos').click( function() {
$('.block_event, .block_link, .block_photos').hide();
$('.block_videos').toggle();
});
Any ideas how to reduce code size? Also, this script isn't very flexible. Imagine to add two new buttons and blocks.
like Sam said, I would use a class that all the blocks share, so you never have to alter that code. Secondly, you can try 'traversing' to the closest block, therefore avoiding it's name. That approach is better than hard coding each specific block, but if the html dom tree changes you will need to refactor. Last, but best, you can pass in the class name desired block as a variable to the function. Below is something you can copy paste that is close to what you started with.
$('.myAddButtonClass').click( function() {
$('.mySharedBlockClass').filter(':visible').hide();
//find a good way to 'traverse' to your desired block, or name it specifically for now.
//$(this).closest(".mySharedBlockClass").show() complete guess
$('.specificBlockClass').show();
});
I kept reading this "When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button" thinking that my eyes were failing me when Its just bad English.
If you want to make it more dynamic, what you can do is add a common class keyword. Then
when the click event is raise. You can have it loop though all the classes that have the
keyword and have it hide them all (except the current one that was clicked) and then show the current one by using the 'this' keyword.
you can refer below link,
http://chandreshmaheshwari.wordpress.com/2011/05/24/show-hide-div-content-using-jquery/
call function showSlidingDiv() onclick event and pass your button class dynamically.
This may be useful.
Thanks.
try this
$('input[type=button]').click( function() {
$('div[class^=block]').hide(); // I resumed html block is div
$(this).toggle();
});
Unfortunatly I couldn't test it, but if I can remember right following should work:
function toogleFunc(clickObject, toogleTarget, hideTarget)
{
$(clickObject).click(function()
{
$(hideTarget).hide();
$(toogleTarget).toggle();
});
}
And the call:
toogleFunc(
".btn_add_videos",
".block_videos",
".block_event, .block_link, .block_photos"
);
and so far
Assuming the buttons will only have one class each, something like this ought to work.
var classNames = [ 'btn_add_event', 'block_link', 'block_photos', 'block_videos' ];
var all = '.' + classNames.join(', .'); // generate a jquery format string for selection
$(all).click( function() {
var j = classNames.length;
while(j--){
if( this.className === classNames[j] ){
var others = classNames.splice(j, 1); // should leave all classes but the one on this button
$('.' + others.join(', .')).hide();
$('.' + classNames[j]).toggle();
}
}
}
All the buttons have the same handler. When the handler fires, it checks the sender for one of the classes in the list. If a class is found, it generates a jquery selection string from the remaining classes and hides them, and toggles the one found. You may have to do some checking to make sure the strings are generating correctly.
It depends by how your HTML is structured.
Supposing you've something like this
<div class="area">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
...
<div class="sender">
<a class="one"></a>
<a class="two"></a>
<a class="three"></a>
</div>
You have a class shared by the sender and the target.
Your js would be like this:
$('.sender > a').click(function() {
var target = $(this).attr('class');
$('.area > .' + target).show().siblings().hide();
});
You show your real target and hide its siblings, which aren't needed.
If you put the class postfixes in an array, you can easily make this code more dynamic. This code assumed that it doesn't matter in which order toggle or hide are called. If it does matter, you can just remember the right classname inside the (inner) loop, and toggle that class after the loop.
The advantage to this approach is that you can extend the array with an exta class without needing to modifying the rest of the code.
var classes = new Array('videos', 'event', 'link', 'photos');
for (var i = 0; i < classes.length; ++i)
{
$('.btn_add_' + classes[i]).click(
function()
{
for (var j = 0; j < classes.length; ++j)
{
if (this.hasClass('btn_add_' + classes[j]))
{
$('.block_' + classes[j]).toggle();
}
else
{
$('.block_' + classes[j]).hide();
}
}
});
}
You could make this code more elegant by not assigning those elements classes like btn_add_event, but give them two classes: btn_add and event, or even resort to giving them id's. My solution is based on your description of your current html.
Here is what I think is a nice flexible and performant function. It assumes you can contain your links and html blocks in a parent, but otherwise it uses closures to precalculate the elements involved, so a click is super-fast.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>
<script type="text/javascript">
// Enables show/hide functionality on click.
// The elements within 'container' matching the selector 'blocks' are hidden
// When elements within 'container' matching the selector 'clicker' are clicked
// their attribute with the name 'clickerAttr' is appended to the selector
// 'subject' to identify a target, usually one of the 'blocks'. All blocks
// except the target are hidden. The target is shown.
//
// Change clickerAttr from 'linkTarget' to 'id' if you want XHTML compliance
//
// container: grouping of related elements for which to enable this functionality
// clicker: selector to element type that when clicked triggers the show/hide functionality
// clickerAttr: name of the DOM attribute that will be used to adapt the 'subject' selector
// blocks: selector to the html blocks that will be shown or hidden when the clicker is clicked
// subject: root of the selector to be used to identify the one html block to be shown
//
function initToggle(container,clicker,clickerAttr,blocks,subject) {
$(container).each(
function(idx,instance) {
var containerElement = $(instance);
var containedBlocks = containerElement.find(blocks);
containerElement.find(clicker).each(function(idxC, instanceClicker) {
var tgtE = containerElement.find(subject+instanceClicker.getAttribute(clickerAttr));
var clickerBlocks = containedBlocks.not(tgtE);
$(instanceClicker).click(function(event) {
clickerBlocks.hide();
tgtE.toggle();
});
});
// initially cleared
containedBlocks.hide();
}
);
}
$(function() {
initToggle('.toggle','a.link','linkTarget','div.block','div.');
});
</script>
</head>
<body>
Example HTML block toggle:
<div class="toggle">
a <br />
b <br />
c <br />
<div class="A block"> A </div>
<div class="B block"> B </div>
<div class="C block"> C </div>
</div> <!-- toggle -->
This next one is not enabled, to show scoping.
<div class="toggle2">
a <br />
<div class="A block">A</div>
</div> <!-- toggle2 -->
This next one is enabled, to show use in multiple positions on a page, such as in a portlet library.
<div class="toggle">
a <br />
<div class="A block">A</div>
</div> <!-- toggle (2) -->
</body>
</html>