Remove parent without an id or class using JQuery - javascript

So I have some html that looks like the following:
<div class='something unknown' id='something_unknown_1'>
<button onClick='removeParent(self)'>Remove me and my parent div</div>
</div>
<div class='something unknown' id='something_unknown_2'>
<button onClick='removeParent(self)'>Remove me and my parent div</div>
</div>
...and so on. How exactly would I reference the button that fired the onClick without knowing the id of the button? I would like to eventually have my removeParent(self) method look like:
buttonThatWasClicked.parent().remove();

You can use this to reference to the button that was clicked inside the click handler.
$("button").click(function(){
removeParent($(this));
});
function removeParent(buttonThatWasClicked){
buttonThatWasClicked.parent().remove();
}

I would add a class to the buttons so the function does not get bound to every button on the page only the ones you would like it to.
<div class='something unknown' id='something unknown'>
<button class="myClass">Remove me and my parent div</div>
</div>
<div class='something unknown' id='something unknown'>
<button class="myClass" >Remove me and my parent div</div>
</div>
Then use the jquery class selector to bind a function that removes the parent.
$(".myClass").click(function(){
$(this).parent().remove();
});
Demo: http://jsfiddle.net/cXLqK/

If you have onclick on HTML nodes (i.e. not set via jQuery):
<div class='classA' id='idA'>
<button onclick='removeParent(this)'>Remove me and my parent div</div>
</div>
<div class='classB' id='idB'>
<button onclick='removeParent(this)'>Remove me and my parent div</div>
</div>
then this will work:
removeParent = function(e) {
$(e).parent().remove();
}
Working example:
http://jsfiddle.net/VEETt/

Related

Multiple toggling buttons and texts with a single function

$(document).ready(function(){
$("button").click(function(){
$("#answer").toggle(1000);
});
});
this only works for the IDs "answer" and "button", the challenge for me its getting multiple pairs of these IDs (answer1 - button1, answer2 - button2, and so on) to work with this single function
You haven't included the relevant HTML so I can only guess/assume what it might look like in my demo/example.
For multiple elements it is best to use a class to group them.
$(document).ready(function() {
$(".answerTog").click(function() {
$(this).prev('.answer').toggle(1000);
});
});
.Question {
display: block;
margin-bottom: 5px;
}
.answer {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Question">
<input type="text" placeholder="Question One" />
<span class="answer">Question One Answer.</span>
<button class="answerTog">See Answer</button>
</div>
<div class="Question">
<input type="text" placeholder="Question Two" />
<span class="answer">Question Two Answer.</span>
<button class="answerTog">See Answer</button>
</div>
<div class="Question">
<input type="text" placeholder="Question Three" />
<span class="answer">Question Three Answer.</span>
<button class="answerTog">See Answer</button>
</div>
If your button is before the answer then you can simply use
$(this).next('.answer').toggle(1000);
$(this) will target the specific element used to trigger the function call, in this instance the button being clicked.
.prev('.answer') will target the previous element with the class name of answer
.next('.answer') will target the next element with the class name of answer
JsFiddle Demo
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
You are currently using an ID property to call that button ($('#')) You want to call them by classes.
IDs should be unique and only used in 1 DOM element.
Trying to use ID the script will only pick the 1st element it comes across; and the code will only work for that one button.
With classes you create an Object for all of your elements, with jQuery you just have to call the element by its class, and run the code normally - I note this because in JS you would have to add the index to the element call.
For example:
<canvas id="main"></canvas>
<div class="elem"></div>
<div class="elem"></div>
<div class="elem"></div>
<script>
var canvas = $('#main'), // return 1 element
elements = $('.elem'); // return 3 elements
</script>
So for anything that involves multiple elements you must call them by class or tag name.
In vanilla JS you would look at something like this:
<script>
var elem = document.querySelectorAll('.elem');
console.log(elem[0]);
</script>
So, your code would then just need to call those elements by class; and you can set custom classes for different purposes.
$(document).ready(function() {
var btns = $('.btn');
btns.click(function() {
btns.toggle(1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>
<button class="btn">Button</button>
<button class="btn">Button</button>
<button class="btn">Button</button>

Is it bad practice to hold information in the id of an HTML element?

Let's say I have a template and I want to loop and create div's. I want to listen to clicks on the buttons contained in each of these divs:
<div class="repeatedDiv">
<button class="reply-button">
</div>
$('.reply-button').on('click',function(e)...)
I want to make the reply button function specific to the div that it was selected on. Would it be bad to have something like:
<div class="repeatedDiv">
<button class="reply-button" id="reply-{{this.id}}">
</div>
Don't make it more complicated than it really is
$(document).on('click', '.reply-button', function(e){
var divClicked = $(e.target).closest('.repeatedDiv');
// do something with clicked div
// var divClicked is the div elmt that contains the button that was clicked
// doing it this way you might not even need an id at all
console.log(divClicked.attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="repeatedDiv">
<button class="reply-button">div1</button>
</div>
<div id="div2" class="repeatedDiv">
<button class="reply-button">div2</button>
</div>
<div id="div3" class="repeatedDiv">
<button class="reply-button">div3</button>
</div>
And if you do need an id when creating a new div create it dynamically with e.g.
var newID = "id-" + Date.now();
console.log(newID);

jquery multiple show/hide buttons

I am trying to convert a lot of JavaScript to jQuery and I have a task that I believe has a simple jQuery shortcut, but I don't know what it is and I haven't been able to find an example.
I have a page with many toggled divs. They are in the form that follows where ### is a unique integer for each pair.
<button class='togglebutton' onclick="toggle('div###');">+</button>
<div id='div###'>...some text...</div>
I'd assume the shortcut is something like:
$('.togglebutton').onclick(function() {
var divid = '#div'+?????;
$(divid).toggle();
});
My theory... if I give each button an id, such as 'button###', then I can use substring to get the value after the word 'button', something like:
$(this).id().substring(6,3);
Obviously, that didn't work. So, I figured that I should ask if there is a simple shortcut in jQuery to pair a showhide button with a separate div.
You may want to do this no matter where your div locates http://jsfiddle.net/tg5op333/25/
HTML
<button class='togglebutton' data-id="1">+</button>
<div id='1' style="display:none">...some text...</div>
<button class='togglebutton' data-id="2">+</button>
<div id='2' style="display:none">...some text...</div>
<button class='togglebutton' data-id="3">+</button>
<div id='3' style="display:none">...some text...</div>
<button class='togglebutton' data-id="4">+</button>
<div id='4' style="display:none">...some text...</div>
JS:
$('.togglebutton').click(function() {
$("#"+ $(this).data('id')).toggle();
});
If the HTML is ordered like you show in your question, then use:
$('.togglebutton').click(function() {
$(this).next().toggle();
});
$('.togglebutton').click(function() {
$(this).next().toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class='togglebutton'>+</button>
<div id='div1'>...some text...</div>
<button class='togglebutton'>+</button>
<div id='div2'>...some text...</div>
<button class='togglebutton'>+</button>
<div id='div3'>...some text...</div>
Two ways:
1) You can use some common class attribute to all dives and select all using that.
Or
2) Or else you can use this wildcard selector :
$("[id^=div]")
It gives you all divs whose id starts with div.

Select div children

I want to select the child of a div using jquery. I try with children() but didn't work
<div class="main" id="this_456" onclick="change(456)">
<div id="title">some text</div>
<div id="body">some text as well</div>
</div>
javascript
function change(id)
{
$('#this_'+id).children("#body").fadeOut();
}
Your code works if you specify 456 as the argument rather than this_456 (see: http://jsfiddle.net/aLxTz/).
However, since <div id="body"/> is identified by ID (#body) it's redundant to look for it inside and other element - it should be unique document-wide. Use the class="" attribute if you expect to have several instances of a body <div/>, e.g. <div class="body">...</div>.
Furthermore, note that the onclick handler has the this variable set to the context element. Since this is the element in question itself, you could write
<div class="main" id="this_456"> ... </div>
$(".main").click(function() {
$(this).chlidren(".body").fadeOut();
});
<div class="main" id="this_456" onclick="change(this)">
<div id="title">some text</div>
<div id="body">some text as well</div>
</div>
function change(elm) {
$(elm).children("#body").fadeOut();
}
FIDDLE
Try this code:
function change(id) {
$('#this_'+id+ ' > div').find("#body").fadeOut();
}

multiple div using the same class open at once

I am using the javascript function for multiple hide show divs in custom tumblr theme.. my The problem is as the class name is same, if i click on a single div, by default all the div gets show or hide.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$(".toggleme").click(function () {
$(".toparea3").slideToggle("slow");
return false;
});
});
</script>
<a class="toggleme" href="#"><img src="http://www.abc.com/images/share.png"></a>
<div class="toparea3" style="display:none;">
<div class="share-bar clearfix" style=" margin-top:3px;margin-left: -2px;width: 380px;height: 50px;">
<div class="share-bar-buttons">
<div class="share-bar-facebook">
<iframe src="http://www.facebook.com/plugins/like.php?href={URLEncodedPermalink}&layout=button_count&show_faces=false&width=110&action=like&font=lucida+grande&colorscheme=light&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:110px; height:21px;" allowTransparency="true"></iframe>
</div>
</div>
<div style="margin-left:80px;margin-top: 15px;" class="share-bar-twitter">
<a href="http://twitter.com/share" class="twitter-share-button"
data-url="{Permalink}"
{block:Twitter}data-via="{TwitterUsername}"{/block:Twitter}
data-related="stylehatch:Premium Tumblr Themes by #newezra"></a>
</div>
<div style="float: right;margin-top:-25px;" class="share-bar-shorturl">
<div class="linktumb">
http://www.tumblr.com/xdrs2sf
</div>
</div>
</div>
</div>
Assuming you have multiple "toggleme" buttons, if they're all in the format where you have a toggleme button and then a toparea3, you could do something like this:
$('.toggleme').click(function(){
$(this).next().slideToggle('slow');
return false;
});
The "next" function gets the next element in the DOM, which is the element you want to expand.
Edit: (nevermind the .children)
try using the .closest selector, or the .next selector someone else suggested. Just remember to provide the selector .toparea3 to make sure that only that class opens, not just any closest/next element.
$(document).ready(function() {
$(".toggleme").click(function () {
$(this).closest(".toparea3").slideToggle("slow");
return false;
});
});
I would recommend the following:
Place the 'a' and the corresponding 'div' in a parent 'div'. Something like this:
<div>
<a class='toggleMe' />
<div class='toparea3 />
</div>
Then you can update your inner selector to be:
$('.toggleMe').click(function(evt){
evt.preventDefault();
var parent = $(this).closest('div');
$(".toparea3", parent).slideToggle("slow");
}
My Recommendation is to give the div an id, and make the anchor element's href point to it:
<script>
$(document).ready(function() {
$(".toggleme").click(function () {
$(this.hash).slideToggle("slow");
return false;
});
});
</script>
<a class="toggleme" href="#toparea3_1"><img src="http://www.abc.com/images/share.png"></a>
<div id="toparea3_1" class="toparea3" style="display:none;"></div>
This since the hash is given in the form #toparea3_1 that is a valid jQuery selector that selects on ID, and can be used directly.

Categories