Get child id onclick - javascript

I have a child ID located within my "myDiv" that is randomly generated.
Assuming it is 'xxx' in this case, this is how the code would look like:
<div id="myDiv">
<div id="xxx"><p>0</p></div>
</div>
I have several of these myDivs that appear on my page, however the randomly generated ID is never the same. Thus, I am trying to retrieve that ID and then change the html for only that ID from 0 to 1. Like so:
$('#myDiv').click(function(){
// 1) retrieve id
// 2) $('id').html("<p>1</p>")
});
Thanks!

I'd suggest, based on the limited information in the question:
// attaching the click event-handler to the 'myDiv',
// firing the anonymous function if the clicked-element has
// an id attribute:
$('#myDiv').on('click', '[id]', function(){
// this/$(this) refers to the clicked element,
$(this)
// finds the <p> elements, and sets its text to:
.find('p').text(function (i,t) {
// i: the index of the element,
// t: the current-text of the element
// +t converts to a number, then we add 1 to that number:
return +t + 1;
});
});
References:
find().
on().
text().

You could use first() to find the first div in your child which matches the selector
$(this).first('div[id]').html('your html')

You can use the first selector and children().
You don't actually need to get the ID:
$('#myDiv').click(function(){
$(this).children(':first').html("<p>1</p>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
<div id="xxx"><p>0</p></div>
</div>

$('#myDiv').click(function(){
$(this).children(':first').html("<p>1</p>")
});
try this

$('#myDiv').click(function(){
var id = $(this).find('div').attr('id');
alert("The id is: "+id);
$('#' + id).html('<p>YOUR NEW HTML</p>')
});

Related

How to get specific div through this?

I build a method that allow me to return the clicked element by the user, something like this:
$('#button2').on('mouseover', function()
{
console.log(this);
}
this return:
<tr id="res-7" class="entry border-bottom" rel="popover" data-original-title="" title="">
<td style="padding-left: 10px">
<div class="name"><strong>Test</strong></div>
<div class="description">Foo</div>
</td>
</tr>
essentially my target is get the content of div name and div description, someone could explain how to do this? Thanks.
Something like this: jsfiddle
$(document).on("mouseover","tr", function(){
var name = $(this).find(".name").text();
var description = $(this).find(".description").text();
console.log("Name: "+name+"\nDecsription: "+description);
})
Don't forget ID of each element must be unique so your code is not correct because "#button2" must be unique, so this is always #button2 in your function.
Note the difference between text() and html(). I used .text() to get just the text without "strong" code. If you need it use html().
You could use innerHTML
$(this).find('name').innerHTML; //returns "test"
$(this).find('description').innerHTML; //returns "foo"
This will find the class within the current element, and return the values you need.
Since you already have an id on your element, accessing the name and description attributes is easy:
$('#button2').on('mouseover', function() {
var $res7 = $('#res-7');
// Access the two divs
var name = $res7.find('.name').text(); // or .html()
var description = $res7.find('.description').text(); // or .html()
// Print them out
console.log(name);
console.log(description);
});
Of course, this block of code should be inside a jQuery ready event handler.
I'm sure there is a cleaner way, but this should get you what you want.
$('#button2').on('mouseover', function()
{
console.log($(this).find(".name").html());
console.log($(this).find(".description")).html());
}

JQuery clone is not working with class selector

Fiddle
I am trying to clone a span from the onClick() function of a button. First time this works fine but when I try second time it is not cloning. What am I doing wrong?
Here is the essence of my code.
$(document).ready(function(){
$('.addmachinerow').on('click',function(){
var edcname = $('.edc_name option:selected').val();
var machine_description = $("input[name='machine_description'").val();
var capacity = $("input[name='capacity'").val();
var voltage_level = $("input[name='voltage_level'").val();
var powertype = $("select[name='typeofpower'").val();
var edcautovalue = $('.ecaddingspan').attr('data-value');
//if($('#bank_increment').html() == '') $('#bank_increment').html('0'); else $('#bank_increment').html(parseInt($('#bank_increment').html())+1);
//if($('#bank_clickededit').html() == '') var bank_increment = $('#bank_increment').html(); else var bank_increment = $('#bank_clickededit').html();
$('.ecaddingspan').clone().appendTo('.edcparent');
//$('.bankname, .bankbranch , .IFSCcode , .bankaccno , .accsincefrom').val('');
var edc_details = {'edcname' : edcname, 'machine_description' : machine_description, 'capacity' : capacity, 'voltage_level' : voltage_level, 'powertype' : powertype }
//$('.bank_details_array').append(JSON.stringify(bank_details)+'&&');
});
});
Additionally:
How can i clone the entire sets on clicking the Total clone button ?
I need to save the values in array with different names. Is that possible ?
How can i clone the entire sets on clicking the Total clone button ?
You've to use event delagtion on() instead :
$('body').on('click','.addmachinerow', function(){
//Event code
})
Since the new .addmachinerow added to the page dynamically after the clone.
I need to save the values in array with different names is that possible ?
I suggest the use of the array name [] like :
<input name='machine_description[]' />
<input name='voltage_level[]' />
Hope this helps.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('.cloneitem').not('.cloned').clone().addClass('cloned').appendTo('body');
});
});
</script>
</head>
<body>
<p class="cloneitem">This is a paragraph.</p>
<button>Clone all p elements, and append them to the body element</button>
</body>
</html>
The issue is a common misconception of JQuery selectors. If you play with ID selectors then switch to class selectors then you often don't notice a difference in behaviour. The ID selector doc says
ID Selector: If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM
whilst for the class selector
Class Selector: Selects all elements with the given class.
What this means is that when you clone the target element you get away with a subsequent ID selection (JQuery ignores the duplicates) but a subsequent class selection will trip you up if you were not expecting JQuery to return multiple matches. Class selectors are great for grouping elements but not so great for cloning.
While I am on the soap box - whenever you use the clone function you should consider and fix the potential duplicate ID and un-required class duplicates that you are producing. Duplicate ID's are definitely bad show - duplicate classes may actually be by design but you should still consider them.
In the code sample below I assign the class iAmSpartacus to the original span which the onClick() function then clones. Each clone also gets the iAmSpartacus class so I remove it from each new clone to ensure that the $(".iAmSpartacus") selector always returns a maximum of one element. The spans show their current class property to prove the point.
// this runs one - shows us classes of original span
var origSpan=$(".iAmSpartacus")
origSpan.html("My classes are: " + origSpan.prop("class"))
$("#daButton").on("click", function(e) {
var newSpan = $(".iAmSpartacus").clone();
newSpan.removeClass("iAmSpartacus"); // remove the dup targetting class
newSpan.appendTo('.edcparent');
newSpan.html("My classes are: " + newSpan.prop("class"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="daButton">Click me</button>
<div class="edcparent" style="border: 1px solid red;">
<span class="ecaddingspan iAmSpartacus" style="display: block;">I am a span</span>
</div>

Jquery assign second child attribute

Is there a way to assign nested div attribute with variable? Like
<div>
<div>
123456
</div>
</div>
Become
<div>
<div sectionid="123">
123456
</div>
</div>
BTW above component will be created by JavaScript.
I've tried something like this, but it didn't work.
var a = $('<div><div>123456</div></div>');
a.eq(":nth-child(2)").attr("sectionid", "123");
Try this snippet.
//FOR DOM HTML
console.log("FOR DOM HTML");
//1st way
$('#input > div').find('div').attr("sectionid","123");
console.log($('#input').html());
//2nd way
$('#input > div > div').attr("sectionid","321");
console.log($('#input').html());
//JS HTML
console.log("FOR JS OBJECT");
var input = $('<div><div>123456</div></div>');
//1st way
input.eq(0).children().attr('sectionid', '456');
console.log(input[0].outerHTML);
var input = $('<div><div>123456</div></div>');
//2nd way
$(input[0]).children().attr('sectionid', '789');
console.log(input[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input">
<div>
<div>
123456
</div>
</div>
</div>
nth-child(2) maches elements that are the second child element of their parent. This is not the case for your div, it is the first element of the parent div.
.eq finds an element at a specific index. It is not the place to pass a selector.
The child selector, >, will find a child element, i.e. div>div will find a div that is an immediate child of a div.
Note that the code you've provided, $('<div></div>123456<div></div>');, doesn't create a DOM tree like the one you've pasted.
Update, now that the code is edited, the value of a is a div with a child div. Since a.find will perform a search within a, you don't have to use a child selector, but can find the div immediately:
a.find('div')
Just apply attribute to children. No complicated 'find', eq(), etc.
var a = $('<div><div>123456</div></div>');
a.children().attr('sectionid', '123');
$('body').append(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Why don't you add it in the first place? Not clear if you add it later!
$(document).ready(function() {
var sectionid = "123";
var a = $('<div><div sectionid="' + sectionid + '">123456</div></div>');
$('body').append(a);
});
div[sectionid]{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this - I have added comments to the code to explain what is happening.
Inspect the element to see that the attribute is added
var a = $('<div><div>123456</div></div>'); // change this to match the structure you want
a.children() // .children gets the direct descendant (which should be the nested div
.eq(0) // gets the first in the array that is returned (if there are multiple direct descendents) - it is a 0 based index selector
.attr('sectionid', '123');
$('body').append(a)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
More information about .children()
More information about .eq()
try it :
$(document).ready(function(){
$("div").eq(1).attr("sectionid","123");
})

How do I get the ID of a particular class using jQuery?

I have some div elements having class name hover, these div elements have parent divs having class name hoverparent but the id's of these parent elements are different.
Is it possible to get the ID of respective .hoverparent element while hovering on my .hover div elements?
I tried to get this by:
$('.hoverparent').attr('id')
But it gives the same first parent id every time.
Structure is like:
<div class="hoverparent" id="hover-1">
<div class="hover">ABC</div>
</div>
<div class="hoverparent" id="hover-2">
<div class="hover">DEF</div>
</div>
You need to use the parent or closest functions to traverse up the DOM tree to find the "parent" element you are looking for:
$(".hover").hover(function() {
var $parent = $(this).closest(".hoverparent");
alert($parent.attr("id"));
});
The difference between parent and closest is that the first will only work if the .hoverparent element is the immediate parent of the .hover element; closest will search upwards through all ancestors to find it.
try $(this).parent().attr('id') , in your hover callback.
$('.hover').mouseover(function() {
$(this).parent().attr('id');
});
don't call your class hover. this should work
$(".hover").hover(
function () {
var id = $(this).parent().attr('id');
});
Add each loop like this :
$(".hoverparent").each(function(){
var id=$(this).attr("id");
alert(id);
});
Use the parent method in the handler for the hover event:
$('.hover').hover(function(evt){
var par = $(this).parent().attr('id');
//Now do with ID what you need
},
function(evt){
//presumably you don't need anything for mouseout
});
You can try the parent() method.
Like this:
$('a').click(function(){
var parentId = $(this).parent('div.hoverparent').attr('id');
});
Try the following:
$('.hover').hover(function() {
var parentID = $(this).parent().attr('id'); alert(parentID);
});
$(".hover").hover(function(){
console.log($(this).closest(".hoverparent").attr("id"));
});
here is the fiddle http://jsfiddle.net/9dJJ9/1/show/

How to use jquery to select all elements that have two specific attributes

I have some markup where a lot of id's have an id attribute, as well as innerText. I want to select each of these elements, performing a function on the id.
How do I do that?
Something like this?
$('[id]:not(:empty)').each(function(i, el) {
// do stuff
});
Give them a common class:
HTML
<div id="first" class="all"></div>
<div id="second" class="all"></div>
<div id="third" class="all"></div>
jQuery
$('div.all').each(function(index){
processid(this.id);
});
If you are talking about selecting elements whose id (or some permutation of it) is included in its text then
$('[id]').filter(function(){
return $(this).text().indexOf( this.id ) >= 0; // the this.id should be altered to match the permutation you seek ..
}).css('color','red'); // turn those to red
After you comment to #lonesomeday (at the question comments) here is what to do ..
$('[id]').each(function(){
processid(this.id);
});
First select by a regular ID selector and then loop over that selection by filtering .text() non-empty.
$("[id]").each(function() {
if ($(this).text() != "") {
// do stuff
}
});

Categories

Resources