Getting element attribute with jQuery .attr() method - javascript

I'm using jQuery .attr() method to get the value of an element's attribute, in this case an id, and storing it into a string. Then I replace "info" to "article" in the string to hide and show elements in my page.
My HTML code looks like this:
<div id="navigator">
<div id="info_01">Lorem Ipsum
<div id="info_02">Lorem Ipsum</div>
</div>
<div id="info_03">Lorem Ipsum</div>
</div>
jQuery code:
$('#navigator>div, #navigator>div>div').click(function(){
var variable=$(this).attr('id');
var variable2=(variable.replace("info", "article"));
console.log(variable2);
$("#another_div").hide();
$("#"+variable2).show();
});
I'm outputting log to console, and when I click on parent divs inside #navigator such as #info_01 and #info_03 it prints only the id of the div I clicked, but when I click on child elements in #navigator such as #info_02, it prints two lines:
article_02
article_01
As you can see, the first one is from the first div I click on, but since I'm also clicking on its parent, it outputs the parent's id.
I only need to output one id, the one from the element I click on, and not its parent's id.
How can I do that?

Use .stopPropagation(). This prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. Read more on https://api.jquery.com/event.stoppropagation
$('#navigator>div, #navigator>div>div').click(function(e){
var variable=$(this).attr('id');
var variable2=(variable.replace("info", "article"));
console.log(variable2);
$("#another_div").hide();
$("#"+variable2).show();
// propagate
e.stopPropagation();
});

Related

Delete only the particular Div Id

<div id="#("Bottomgrid)" class="dgd2"></div>
var element = document.getElementById("#Bottomgrid");
element.empty();
$('.dgd2').empty()
Instead of deleting only Bottom grid its also removing other Div present in the screen.
jQuery .remove() will remove the set of matched elements from the DOM.
While jQuery .empty() will remove all child nodes of the set of matched elements from the DOM.
Considering if you have your HTML as below :
<div id="Bottomgrid" class="dgd2"></div>
and you want to remove div with id="Bottomgrid"
Then your javascript code will be :
$("#Bottomgrid").remove();
//This is not required as far as I see
//$('.dgd2').empty()
If you have a HTML structure like this:
<div class="holder">
<div id="item1">Hey</div>
</div>
you can simply just use this pure JavaScript code to remove the "item1" element:
var element = document.getElementById("item1");
element.parentNode.removeChild(element);
.empty() doesn't remove element it only removes elements children. use $('#Bottomgrid').remove()
Javascript :
document.getElementById("Bottomgrid").remove();
Jquery:
$( "#Bottomgrid" ).remove();
you should give the div name properly like Below how I am writing the Id. also you need to check properly which div you are going to delete. Because if a nested div present in your page and you are going to delete the div which is having all the child div inside that , then all respective div going to be deleted .
Html
<div id="bottomgridDiv" class="dgd2">
<div id="parentDiv" class="dgd2">
<div id="childDiv" class="dgd2">
</div>
</div>
</div>
Javascript
var element = document.getElementById("#bottomgridDiv");
In JQuery:-
$("#bottomgridDiv").remove();
So now if you wants to delete the bottomgridDiv then what ever the div present inside this is going to delete.

unable to find the item that got user input with dynamically created items

Hi there I am encountering the following problem I have 3 div's dynamically loaded by ajax like so:
<div class="item" id="item1"> // Dynamically loaded
<input>
<input>
</div>
<div class="item" id="item2"> // Dynamically loaded
<input>
<input>
</div>
<div class="item" id="item3"> // Dynamically loaded
<input>
<input>
</div>
$(document).on('change', '.item', function() {
});
What I want to achieve is when I make a change on the input of one of the three div's, I wanna know where the input was provided. Because the elements are dynamically loaded I can't use a direct selector but I have to use $(document).on and because I dont make use of the direct selector I can't make use of (this). How do I find out in what item changes have been made?
Thanks in advance!
The first argument of the handler - for instance e - would receive the event if it is declared. Then the e argument is having target property which gives you the HTML element on which the event originated. So this would give you a reference to the changed input:
$(document).on('change', '.item', function(e) {
var targetInput = e.target;
var parent = $(targetInput).closest("div.item");
// Do something ...
});
According to your HTML, each div is having different id, Hence you can get the div Id on change of the input. Please test this piece of code and test.
$("input").on('keyup', function(){
//Get the parent div id,
var changeDivID = $(this).parents('div').attr("id");
alert(changeDivID);
});

Recieving two values from data attribute one being undefined

I am trying to link to divs together by linking the data-attribute name with the id but seem to receive an error
<div class="pod-container grid_3" data-name="#george">
<div class="pod">
<img src="img/example1.png" alt="">
</div>
</div>
<div id="george">Hello World</div>
I'm referencing jQuery 1.8.3 and using the following code to identify the data attribute on the div i click
<script>
$('.pod-container').click(function(){
var identifyId = $(this).data('name');
console.log(identifyId);
//$(identifyId).show();
});
</script>
but when it is logged in the console I get.
#george testdoc.html:123
undefined testdoc.html:123
You've got two elements with class "pod". One of them has a data-name attribute, and one doesn't. Each click will trigger the event handler on both elements.
Just grab the elements that have the data-name. What you're currently doing is targeting just .pods which may or may not have data-name. With the below code, you're just being specific.
$('.pod[data-name]').click(function(){
var identifyId = $(this).data('name');
console.log(identifyId);
//$(identifyId).show();
});
You have 2 elements with the pod class and are getting 2 events fire. The inner div does not have a data-name attribute.

When a Div class is clicked, alert it's inner content's Div Class

How do i even put these, let me try. In the following sets of codes, i want to click 'parentclass' and have an alert value of 'child1' and when i click the class below it which is 'Parent 2' have an alert fire with a value of 'child2'
So this must alert the content of that class only and not the entire class.
Here's some Javascript in Jquery.
var childclass = $('.childclass').html();
$('.parentclass').click(function(e) {
alert (childclass)
});
$('.childclass').click(function(e) {
e.stopPropagation()
e.preventDefault()
});
And HTML
<a href="" onClick="return false">
<div class='parentclass'>
Parent 1
<div style="display:none" class="childclass">child1</div>
</div>
</a>
<a href="" onClick="return false">
<div class='parentclass'>
Parent 2
<div style="display:none" class="childclass">child2</div>
</div>
</a>
This line var childclass = $('.childclass').html(); doesnt make sense as it doesn't know which element in particular you mean. The result of that will just be child1child2 which is just a concatenation of the .html() of all the elements with class childclass. This is obviously not what you want.
Therefore you should dynamically find the child with a class of childclass upon receiving the click event.
$('.parentclass').click(function(e) {
alert($(this).find('.childclass').html())
});
Also, you should know that your child class event handler is useless as we don't care if the event gets propogated downwards. If you DID care, then your e.stopPropagation() and e.preventDefault() should be in the event handler of the parent class.
You need to fetch the html of the clicked parent element within the click handler
$('.parentclass').click(function (e) {
alert($(this).find('.childclass').html())
});
$('.childclass').click(function (e) {
e.stopPropagation()
e.preventDefault()
});
Demo: Fiddle
Several ways you can go about this.
First, if your HTML will not be dynamic (elements already exist when page loads), then you can select elements by the parent class name and assign click event as so:
$('.parentclass').click(function(e) {
// the first variable here is selecting the inner elements having class 'childclass'
// keep in mind, if more than one child having that class is present within this parent, it will select all of them
var child = $(this).find('.childclass');
// here we alert the text of the inner child found
// if it is more than one, you will have undesired results. you may want to specify `.first()`
alert(child.text())
})
For newer jQuery you can also use $('.parentclass').on('click', function(e) {.
If you expect any pieces of parentclass to be dynamic, then you'll want to delegate the event based on either a static parent to the parents or document. This can be like so:
$(document).on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Or, if you have a static (already there when page loads) wrapping element, give it an ID like `parentClassWrapper' and assign the click event dynamically as:
$('#parentClassWrapper').on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Some helpful links:
jQuery API
jQuery Selectors
.click()
.on()
Some info on Event Delegation
jquery on vs click methods
jQuery .on('click') vs. .click() and .delegate('click')
jquery .live('click') vs .click()
I made several adjustments to your html that are worth noting. There's no need for the <a> tag. Don't use inline js - onlick in your html. Note that I wrapped the text inside of the div in the <a> tag instead. This markup is more semantic. Also, move your styles to css rather than in the html.
<div class="parent">
<a>Parent 1</a>
<a class="child">child of parent 1 contents</a>
</div>
<div class="parent">
<a>Parent 2</a>
<a class="child">child of parent 2 contents</a>
</div>
css:
.parent > .child { /* good practice: only select an immediate child of the parent */
display: none;
}
The other answers here are using find() to select the child, but I recommend children() instead. For example, if you had additional nested .childs, find() will select them all, but children() will only select direct .childs of the parent, so it is better in this case. I also recommend using the console for debugging rather than alert.
Live demo here (click).
$('.parent').click(function() {
var $child = $(this).children('.child');
var cls = $child.attr('class');
console.log(cls);
$child.show(); //added so that you can click the child
});
$('.child').click(function() {
var html = $(this).html();
console.log(html);
//if you just want the text, use this instead:
var text = $(this).text();
console.log(text);
});

How to select element relative to 'this' in javascript

I have the following:
<div class="tab-pane" id="message">
<textarea rows="4" cols="50" id="send_message" placeholder="Enter text ..."> </textarea>
OK
Cancel
I want to bind the click method to the 'div' element , and when one of the child 'a' elements is clicked do separate things. I am trying to distinguish between them using the button text, but the following is not working:
$(function(){
$('#message').click(function(){
if($(this + ">a").is(":contains(OK)")) {
console.log("OK!!");
How can I fix this?
Okay there are two ways of doing this:
.find(selector)
if(this).find("a").is(":contains(OK)")) {
console.log("OK!!");
OR
$(selector,context)
if("a",this).is(":contains(OK)")) {
console.log("OK!!");
In javascript, this is essentially the context of the current function. In jQuery event callbacks, this is set to be the source element of the event - not the selector string, which is what you are treating it as.
Instead, you want to do a test like: if($("a", this).is(":contains(OK)")) {
This works because the second parameter to the jQuery selector is the context to search in, so you are only searching for the a tags under the source element of the click.
Binding the click element to the Div, then checking the text string of the A tags will make both events happen on every click. You want to bind 2 separate click events on each A tag. Add an ID to each A tag, then try this code
$('#okLinkID').click(function(){
console.log("OK!!");
});
$('#cancelLinkID').click(function(){
console.log("Cancel!!");
});
//Attaches only one listener to the #message div and listens for any 'a' element within it to be clicked.
$('a','#message').on('click',function(){
var $this = $(this),
btnText = $this.text();
console.log(btnText);
});
http://jsfiddle.net/YA7Ds/

Categories