Jquery - Accessing nested child elements - javascript

Assume I have the following HTML -
<DIV id="ParentDiv">
<DIV id="SubDiv1"></DIV>
<DIV id="SubDiv2">
<INPUT id="input">
</DIV>
</DIV>
To access the input element using jquery, it would be simply $("#input"). What I'm trying to do is access it, assuming I only know the ID of the top level div.
Currently I have
$($($("#ParentDiv").children()[1]).children()[0])
Which does seem to work. Is there a cleaner way of writing this, or is the way I am doing it ok?

You would just perform a .find() implicitly or explicitly:
$('#ParentDiv input'); // implicitly
$('#ParentDiv').find('input'); // explicitly
Reference: .find()

You can try:
1. $('#ParentDiv input')
2. $('input', '#ParentDiv')
3. $('#ParentDiv').find('input')

if you need to find the input from SubDiv2 only upon having parentDiv information you can use
$("#ParentDiv div:eq(1) input")
or
$("#ParentDiv div:eq(1)").find("input")
Where eq(1) will get you with the second div inside ParentDiv

Try this:
$('#ParentDiv').find('input');

Many ways to do it. Here is one
$("#ParentDiv > div:eq(1) > input")

how about
$("#ParentDiv :input")

try this
jQuery('#input').val();

Related

How to get elementsByClassName and then inside getElementById

Hi I'm rewriting a script from jQuery to pure JS and I don't know how else could i write this.I want to get attribute of element inside class 'form-basket' with id 'przecenajs' I know getElementsByClassName returns object of elements, and that's probably why I get the error:document.getElementsByClassName(...).getElementById is not a function
but I'm not into JS that much so i might be wrong
price = document.getElementsByClassName('form-basket').getElementById("przecenajs").getAttribute("data-procent");
That because getElementsByClassName returns a HTMLCollection object.
You probably want to use querySelector function:
document.querySelector('.form-basket #przecenajs')
console.log(document.querySelector('.form-basket #przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
or
document.getElementById('przecenajs')
console.log(document.getElementById('przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
Resources
document.querySelector()
Document.getElementsByClassName()
You do not have to select the form-basket first. Since IDs should only be used once inside a document, you can simply selct by id like so:
document.getElementById("przecenajs").getAttribute("data-procent");
I assume you are searching for more than only one tag, because if you wouldn't you could just use document.getElementById() so I think these lines do the job you want, you have to manually create the list with all the attributes to replicate the jquery behaviour:
var priceList = [];
document.querySelectorAll(".form-basket #przecenajs").forEach( (element) =>{
priceList.push(element.getAttribute("data-procent"));
});

I am getting undefined value when i try to get parent id of span

I am getting undefined value when I try to get parent id of span.
This is my code:
<span id="test">sskdfj <span>test</span> asdkfwsfe</span>
$(obj).closest().attr('id');
You have to pass a selector to closest() to get any results from it.
If you want the parent element, use parent(), not closest().
$(obj).parent().attr('id');
Assuming the following HTML:
<div id="test">
<span id="test_2"></span>
</div>
In your code obj is #test_2. You want to get #test. You should give a selector to the closest method to select an element, otherwise jQuery doesn't know what to select.
$("#test_2").closest("#test").attr('ID')
Or, as Quentin stated, use parent instead if that's the element you want to select.
$("#test_2").parent().attr('ID')
Check it out here: FIDDLE
Since you're using jQuery, separate out your JS code and use a class.
<span id="spn8">
<span class="clickable">[This note is for an FMLA condition]</span>
</span>
function changeText1(obj,event) {
var pid = $(this).parent().attr('id');
alert(pid);
}
$('.clickable').click(changeText1); // 'spn8'

How to gain access to an element on the same level in the DOM?

<div id="dad">
<img id="mum">
<input>
</div>
With jQuery, how could i get access to the input element, get is value or set it for example? I can't work out how to access something on the same level.. and i dont want to be using ID's, just parent/child nodes so i can use the code for loads of dad div's
Thanks!
an addition to Zed,
$(this).parent().children('input');
if you give a name to your input field then you can easily select throughout the others,
$(this).parent().children('input[name=my_input]');
then you can give any value as:
$(this).parent().children('input[name=my_input]').val('any value');
Sinan.
var myEl = $("#dad").children(":input");
$(this).parent().children() ?
Try this, to find the first child input element:
jQuery("div").find("input:first")
If i understand question, you would like achieve input from mum leve?
So try $("#mum ~ input")...
BTW, great site to search jquery function by category http://visualjquery.com/ +nice example.
I guess you want to find siblings (node with same depth and same parent and in DOM tree)
$(el).next() - next element (sibling) for all elements in the set
$(el).nextAll - all following siblings
$(el).nextUntil - all following siblings, stop on some condition (not including first "bad match").
Besides, you have next adjacent selector (+) and next sibling selector.
The same about prev, prevAll and prevUntil.
And you even have a siblings method.
Check this out.

How to clear all <div>s’ contents inside a parent <div>?

I have a div <div id="masterdiv"> which has several child <div>s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>s inside the master <div> using jQuery?
jQuery's empty() function does just that:
$('#masterdiv').empty();
clears the master div.
$('#masterdiv div').empty();
clears all the child divs, but leaves the master intact.
jQuery('#masterdiv div').html('');
Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.
$('#masterdiv div').empty();
Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.
I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
The better way is :
$( ".masterdiv" ).empty();
$("#masterdiv div").text("");
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();

Count immediate child div elements using jQuery

I have the following HTML node structure:
<div id="foo">
<div id="bar"></div>
<div id="baz">
<div id="biz"></div>
</div>
<span></span>
</div>
How do I count the number of immediate children of foo, that are of type div? In the example above, the result should be two (bar and baz).
$("#foo > div").length
Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.
I recommend using $('#foo').children().size() for better performance.
I've created a jsperf test to see the speed difference and the children() method beaten the child selector (#foo > div) approach by at least 60% in Chrome (canary build v15) 20-30% in Firefox (v4).
By the way, needless to say, these two approaches produce same results (in this case, 1000).
[Update] I've updated the test to include the size() vs length test, and they doesn't make much difference (result: length usage is slightly faster (2%) than size())
[Update] Due to the incorrect markup seen in the OP (before 'markup validated' update by me), both $("#foo > div").length & $('#foo').children().length resulted the same (jsfiddle). But for correct answer to get ONLY 'div' children, one SHOULD use child selector for correct & better performance
$("#foo > div")
selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:
$("#foo > div").size()
or you can use
$("#foo > div").length
Both will return you the same result
$('#foo').children('div').length
In response to mrCoders answer using jsperf why not just use the dom node ?
var $foo = $('#foo');
var count = $foo[0].childElementCount
You can try the test here: http://jsperf.com/jquery-child-ele-size/7
This method gets 46,095 op/s while the other methods at best 2000 op/s
$('#foo > div').size()
$("#foo > div").length
jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property.
From here: http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/
var divss = 0;
$(function(){
$("#foo div").each(function(){
divss++;
});
console.log(divss);
});
<div id="foo">
<div id="bar" class="1"></div>
<div id="baz" class="1"></div>
<div id="bam" class="1"></div>
</div>
With the most recent version of jquery, you can use $("#superpics div").children().length.
var n_numTabs = $("#superpics div").size();
or
var n_numTabs = $("#superpics div").length;
As was already said, both return the same result.
But the size() function is more jQuery "P.C".
I had a similar problem with my page.
For now on, just omit the > and it should work fine.
$("div", "#superpics").size();
Try this for immediate child elements of type div
$("#foo > div")[0].children.length

Categories