My html is
<input type="text" class='myclass' value="start">
<div>
<input type="text" class='myclass' value="sea">
</div>
<button class="mybutton">Catch</button>
<br/>
<input type="text" value="end" class='myclass'>
and javascript is
$('.mybutton').click(function(){
var text = $(this).prev('.myclass').val();
console.log(text);
});
I want to get the value of immediate previous input value by class name. but the result is undefined.I want to get the value sea. Where is the problem? the working fiddle link is Here >> Thank you.
Immediate previous element of catch button is a div, so you need to do a find() inside that
like this:
$('.mybutton').click(function(){
var text = $(this).prev('div').find('.myclass').val();
console.log(text);
});
I want to get the value of immediate previous input
Well, that's the problem, input is not immediate. you can use prevAll method instead:
$('.mybutton').click(function(){
var text = $(this).prevAll('.myclass').val();
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class='myclass' value="start">
<div>
<input type="text" class='myclass' value="sea">
</div>
<button class="mybutton">Catch</button>
<br/>
<input type="text" value="end" class='myclass'>
Interesting. I have never used the ".prev()" function before. Anyways:
If you read here https://api.jquery.com/prev/ you will find:
"Given a jQuery object that represents a set of DOM elements, the .prev() method searches for the predecessor of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements."
Also:
If no previous sibling exists, or if the previous sibling element does not match a supplied selector, an empty jQuery object is returned.
So in other words, as has been mentioned before, the ".prev()" simply looks for the previous element.
To do what you want to do in the way you want to do it you might want to consider the ".prevAll()" function that is explained here: https://api.jquery.com/prevAll/
But then again since the element you want is actually a child of the previous element and not a direct sibling you might want to consider Beginners' suggestion:
$('.mybutton').click(function(){
var text = $(this).prev('div').find('.myclass').val();
console.log(text);
});
But in fact you should be able to make it slightly simpler by removing the 'div' selector:
$('.mybutton').click(function(){
var text = $(this).prev().find('.myclass').val();
console.log(text);
});
As long as you are certain that your '.myclass' element will be a child of the previous element this should work irregardless of what the parent element is (div, span, whatever)
Related
how to use querySelector to select the parent element from the child?
in my example the HTML structure is like this:
<label>
<input/> <!-- I know only this -->
</label>
and in html what I know is only the child so input.
how can get the parent from child input, so getting the label.
from what I know is easy to get the child from the parent by doing like this parent > child
is there any child < parent? (similar logic).
if isn't possible with querySelector() is there any other way with the javascript API?
use .parentElement or use .closest()
parentElement: https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement
if you want only the parent element.
closest: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
if you want specific tag (this can make you some bugs if not used properly)
const input = document.querySelector("input");
// you get the same result with these 2
console.log(input.parentElement)
console.log(input.closest("label"))
// you can use all the method of element
// like style, classList, etc...
input.parentElement.style.outline = "0.2rem solid red";
<label>
<input type="text" /> <!-- I know only this -->
</label>
First you can get input element, after get parent with function closest():
var inputElement = document.querySelector('input');
var label = inputElement.closest('label');
console.log(label)
<label>
<input type="text" /> <!-- I know only this -->
</label>
get the element by the input tag and then look for its parent. However, be sure to check for the undefined and multiple query results from the below code snippet.
document.querySelector("input").parentElement
I need to skip this querySelector('input') because in certain instances the input will come second instead of first. Is there a way to label an element in HTML as 'skip this'?
You're free to utilize the full power of CSS syntax there. In your example if you only want to get input if it's the first parent's element then query like this:
querySelector('input:first-child');
Or if you want to get precise use :nth-child selector, or even better, :nth-of-type:
querySelector('input:nth-of-type(1)');
But the best solution would be to mark your input with a class or id and use it instead:
querySelector('.myInput');
You can of course combine it with negation selector:
querySelector('.myInput:not(':nth-child(2)')');
querySelector returns the first Element that matches the selector provided in the method. And why wouldn't it? That's what it's supposed to do.
A.E. the below returns the first input tag it can find on the document from the top-down.
document.querySelector("input");
It will always return the first input tag it can find. You have two options to "skip" the node. You can either write a function to recursively check if the input should be skipped( kind of superfluous and bad looking ) or you can simply be more specific with your selector.
Either way you need to give the input element you want to skip some sort of recognizable trait. That can be a name property or a dataset property or a class or an id - anything that you can programatically check for.
//functional example
function ignoreSkippable() {
let ele, eles = Array.from(document.querySelectorAll("input"));
eles.some(elem => !elem.matches('.skippable') ? ele = elem : false);
return ele;
}
console.log( ignoreSkippable() );
// <input value="second input"></input>
//specific selector example
let ele = document.querySelector("input:not(.skippable)");
console.log(ele); // <input value="second input"></input>
<input class="skippable" />
<input value="second input" />
What I am attempting to do is is access hidden object in a div. What happends is a user will click on button that will then perform some task such as delete a user. This may be easier if I show what I have.
<div class="mgLine">
<input type="hidden" name="tenentID" value="1">
<p class="mgName">James Gear</p>
<input type="text" class="mgBill" value="" placeholder="Post Bill Link Here">
Submit Bill
Not Paid
Change Password
Delete User
</div>
What I want the system to do is alert the value of one which it gets from the hidden field when the "submit bill" is pressed.
function alertTest(e){
//e.parentNode
window.alert(e.parentNode.getElementsByTagName("tenentID")[0]);
}
I am attempting to use JavaScript DOM to access the element. I hope this made at least some sense. There will be many of these entries on the page.
You need to use getElementsByName instead of getElementsByTagName
function alertTest(e){
//e.parentNode
window.alert(document.getElementsByName("tenentID")[0]);
}
getElementsByTagName is for selecting elements based on its tag say div, input etc..
getElementsByName
getElementsByTagName
Realizing that you might have multiple div section and your hidden input is the first child you could use these:-
e.parentNode.getElementsByTagName("input")[0].value;
or
e.parentNode.firstElementChild.value;
if it is not the firstCHild and you know the position then you could use
e.parentNode.children(n).value; //n is zero indexed here
Fiddle
The modern method would be to use querySelector.
e.parentNode.querySelector("[name=tenentID]");
http://jsfiddle.net/ExplosionPIlls/zU2Gh/
However you could also do it with some more manual DOM parsing:
var nodes = e.parentNode.getElementsByTagName("input"), x;
for (x = 0; x < nodes.length; x++) {
if (nodes[x].name === "tenentID") {
console.log(nodes[x]);
}
}
http://jsfiddle.net/ExplosionPIlls/zU2Gh/1/
Try this:
function alertTest(e){
alert(e.parentNode.getElementsByName("tenentID")[0].value);
}
I usually set an id attribute on the hidden element, then use getElementById.
<input type="hidden" id="tenentID" name="tenentID" value="1">
then I can use...
var tenentValue = document.getElementById("tenentID").value;
In general, your best bet for accessing a specific element is to give it an ID and then use getElementById().
function alertTest(ID){
alert(document.getElementById(ID).value);
}
Names can be duplicated on a page, but the ids have to be unique.
It's like
<input name="fails[]" type="file" size=40 /><br />
<textarea name="apraksts[]">About</textarea>
<a href="#" onclick="remove(this);return false".....>remove</a>
And the javascript:
function remove(obj){
$(obj).prev('textarea').remove();
$(obj).prev('input').remove();
$(obj).remove();
}
Why it doesnt remove INPUT(why it doesnt remove two objects)?
Thanks..
The documentation for prev says it:
Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
After you remove the <textarea>, that element is a <br>. Since it doesn't match input, the resulting jQuery object contains no elements. You then remove those 0 objects.
I suspect a better approach to the problem would be to wrap all the elements in a <div> (or a container with more suitable semantics for the context) and remove that (instead of removing each element in turn).
Or you can also use prevAll. That will select all previous sibling elements which are then filtered by your selector:
$(obj).prevAll('input').remove();
i have 3 hidden fields in 1 div. when I have reference to this div, how to get 1 of the hidden fields in this div.
This will also work (jQuery):
$('#my_div').find('input[type=hidden]:first')
Assuming you have a DIV, like so:
<div id="mydiv">
<input type="hidden">
<input type="hidden">
<input type="hidden">
</div>
You can use jQuery to do something like this to select all of them:
$('input:hidden','#mydiv');
With that selector, now you have all 3 hidden fields in a jQuery collection. You can pick and choose from there which one you want to use by using several methods:
$('input:hidden:first','#mydiv'); // get first one using first
$('input:hidden:last','#mydiv'); // get last one using last
$('input:hidden','#mydiv').eq(0); // get first one using eq
$('input:hidden','#mydiv').eq(1); // get second one using eq
$('input:hidden','#mydiv').eq(2); // get third one using eq
$('input:hidden:eq(0)','#mydiv'); // get first one using eq in selector
The options are:
first - get the first matched element in the collection.
last - get the last matched element in the collection.
eq(N) - get the Nth matched element, 0 based.
:eq(N) - get the Nth matched element, 0 based, inside the selector string.
I am personally a fan of option 3 as I don't like having too much crap in my selector.
One caveat of the above is that by using the :hidden selector we might match other input elements that are hidden (ie, not visible). If you expect that to happen, or even if you don't, you could do this:
$('input[type=hidden]', '#mydiv').eq(0);
Without any code it's hard to help but i'd say give the hidden field an ID and use:
var hdn = document.getElementById("id");
Or if you're using Jquery use:
var hdn = $("#id");
if it's like this:
<div id="somediv">
<input type="hidden"/>
<input type="hidden"/>
<input type="hidden"/>
</div>
and you're using jquery, you can just write this:
$("#somediv > input[type='hidden']:eq(1)")
and it should return a reference to the 1st hidden field. if you want the 2nd, use "eq(2)" and so forth.
var firstHidden = $("input[type='hidden']:first", ref);
:first pseudo-class and attribute selector
or
var firstHidden = $("input:hidden:first", ref);
:hidden pseudo-class (be careful, because :hidden finds also elements with style="display: none")
or
var firstHidden = $("input[type='hidden']", ref).eq(0);
.eq()
where 'ref' variable is a reference to the DIV element
I would assign a class to the hidden you want to find - a little easier on the programmer looking back on it in 4 years. I'm using "id" as an example of the hidden. Once you find it with jQuery - you can use .val() to get its value.
HTML:
<div id="mydiv">
<input type='hidden' name='mydiv_id' class='idField' value='test1' />
<input type='hidden' name='mydiv_hidden2' class='option2' value='test2' />
<input type='hidden' name='mydiv_hidden3' class='option3' value='test3' />
</div>
jQuery:
//execute on document ready:
$(function() {
var div = $('#mydiv'); //some jquery/dom element "div"
// use the jQuery selector with "div" as our context.
var $hidden = $('input.idField', div);
alert($hidden.val()); // should alert 'test1'
});
For a reference, if you're not using jQuery like the original poster and assuming the structure above:
<div id="mydiv">
<input type="hidden">
<input type="hidden">
<input type="hidden">
</div>
var div = document.getElementById('mydiv');
var inputs = div.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
// Match your input with inputs[i].name, etc.
}