Get nested element by name - javascript

I have a table of elements like this:
<tr id="elementId">
<img name="img" src=""/><br/>
<input name="text" type="text"/><br/>
<input name="button" type="button"/><br/>
</tr>
Each element is exactly the same, except of its id.
I try to update the elements with javascript, but I have no clue how to get the child nodes by their name.
My code:
//get element
var element = list.rows[i];
//update nodes
element.getElementByName("img")[0].src = someImg;
element.getElementByName("text")[0].value = someText;
element.getElementByName("button")[0].value = someOtherText;
The code doesn't work, because element has no function getElementByName.
Is there any other way to get the nodes by their name?

element.querySelector('[name="thename"]') or element.querySelectorAll('[name=2thename"]')

The function is getElementsByName. Elements is plural.
Note that it returns an array-like HTML Collection, so you'll need to grab the first item off it too (with [0]).
Additionally, you might find that your elements aren't actually in your table row as you are missing table cells. Validate your markup: http://validator.w3.org/nu/

In order to select all alements with a tagname in the whole document you may use
listElements = document.getElementsByTagName();
Inside a certain element, you may use
selectedElement = element.getElementsByTagName();
Notice this functions returns an array with the elements selected. If there is only one element, it will be in
listElements[0]
in the first case, or
selectedElement[0]
in the second.

Related

Is there a way to skip a specific CSS selector in HTML when using querySelector in JavaScript?

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" />

How to read attribute using jquery on input variable with variable selector?

I want to reload a particular div, which has an id corresponding to a table element's id... (the div has only one table child).
the alert says tID is undefined.
javascript:
function (msg) {
var tID = $("table", msg).attr('id');
alert(tID);
$("#reloadme_"+tID).html(msg);
}
html:
<div id="reloadme_2036">
<table id="2036" class="customCSSclass">
...table contents...
</table>
</div>
Where have I gone wrong?
find looks for descendants of the current set of elements inside the jQuery object, you should use .filter which filters the elements in the jQuery object itself:
$('<table id="001">[...]</table>')
//the jQuery object will contain a reference to the parsed <table> element,
//so you have to .filter() the jQuery object itself to extract it
Of course, if it is the only element inside the jQuery object, there is no need for filtering. =]
Also, you'd use .find for e.g. looking for tr/tds (or any other element(s)) that are descendant of the table element referenced inside of your jQuery object.
Maybe this is what you're looking for?
function reload(msg) {
var tID = msg.match(/id="(\d{1,4})"/i)[1]; //find 1 to 4 digits in the id attribute
alert(tID); //alerts 2036
$("#reloadme_"+tID).html(msg); //adds the content to the div
}
reload('<table id="2036" class="customCSSclass"> ...table contents... </table>');
If so, what you are likely looking for is javascript's .match() method which will find the id number within a string.
Check out the JSFiddle.
You have to try like this
var msg='<table id="2036" class="customCSSclass"></table>';
alert($(msg).attr("id"));

Is there a method in jQuery that will traverse up the dom tree from an element and check selectors before its parent element

For example:
<div class="mainWrapper">
<div class="FirstLayer">
<input class="foo" value="foo" />
</div>
<div class="SecondLayer">
<div class="thirdLayer">
<input class="fee" />
</div>
</div>
</div>
Lets say I have the input.fee as a jQuery object and I also need to get the value of input.foo.
Now I know I can use a multitude of approaches such as $(this).parents(':eq(2)').find('.foo') but I want to use this one method on layouts which will have varying levels and numbers of nodes.
So I am wondering if there is a method which will simply start from .fee and just keep going up until it finds the first matching element, .prevAll() does not appear to do this. There are many .foo and .fee elements and I need specifically the first one above the .fee in context.
How about this:
$('input.fee').closest(':has("input.foo")')
.find('input.foo').val();
Here's JS Fiddle to play with. )
UPDATE: Kudos to #VisioN - of course, parents:first is well replaced by closest.
This will select the previous input.foo
// self might have siblings that are input.foo so include in selection
$( $("input.fee").parentsUntil(":has(input.foo)").andSelf()
// if input.off is sibling of input.fee then nothing will
// be returned from parentsUntil. This is the only time input.fee
// will be selected by last(). Reverse makes sure self is at index 0
.get().reverse() )
// last => closest element
.last()
//fetch siblings that contain or are input.foo elements
.prevAll(":has(input.foo), input.foo")
// first is closest
.first()
// return jQuery object with all descendants
.find("*")
// include Self in case it is an input.foo element
.andSelf()
.filter("input.foo")
// return value of first matching element
.val()
jQuery.closest() takes selector and does exactly what you need - finds the first matching element that is parent of something. There's also jQuery.parents() that does take a selector to filter element ancestors. Use those combined with find method and you're set.
$('input.fee').closest('.mainWrapper").find('.foo') does the trick, doesn't it?

get id value by index using name jquery

html
<input id="1" name="myText" type="text" value="20"/>
<input id="2" name="myText" type="text" value="30"/>
<input id="3" name="myText" type="text" value="40"/>
How can I get id value by index using name?
The following code snippet is not working
var getVal = $('[name="myText"]').index(1);
jQuery holds the DOM elements in the set like an array so you can use the indexes operator([]) to get the element, or get the jQuery object that wraps the desired element with :eq(n) `.eq(n)`
$('input[name="myText"]:eq(1)').attr('id')
You should mention what to you consider to be index(1) the first or the second:
$('input[name="myText"]:eq(0)').attr('id') // First
$('input[name="myText"]:eq(1)').attr('id') // Second
Or:
$('input[name="myText"]')[0].id // First
If you want the first value, you can filter and use the attr method to get the value of the id attribute.
var getVal = $('[name="myText"]:first').attr('id'); // first id
If you want some other element, you can use eq and choose the zero-based element in the collection.
var getVal = $('[name="myText"]:eq(1)').attr('id'); // second id
My answer refers to accessing elements in the jQuery result object by index. You can use selectors such as :eq indicated in other answers.
However, you can use .get(1) instead of your index.
var id = $('[name="myText"]').get(1).id;
Is equivalent to
var id = $('[name="myText"]:eq(1)').attr('id');
Example: http://jsfiddle.net/HackedByChinese/UmKw6/1/
The second method is the preferred route, since it means you never leave the jQuery result object and thus can chain other jQuery calls in one statement.
var id = $('[name="myText"]:eq(1)').css('color', 'red').attr('id'); // example of chaining jQuery methods. sets the text color to red and then returns the id.

What is the equivalent of jQuery's $(".cell:first") in D3?

I've tried
d3.select(".cell:first")
d3.selectAll(".cell").filter(":first")
d3.selectAll(".cell").select(":first")
but neither work
d3.select(".cell") already selects the first matched element:
Selects the first element that matches the specified selector string, returning a single-element selection. If no elements in the current document match the specified selector, returns the empty selection. If multiple elements match the selector, only the first matching element (in document traversal order) will be selected.
Source: https://github.com/mbostock/d3/wiki/Selections#wiki-d3_select
"How would I get the last item?"
D3 appears to return the results of d3.selectAll() in a collection, positioned in an array. For instance, requesting all paragraphs on the d3 homepage results in:
[ Array[32] ] // An array with a single array child. Child has 32 paragraphs.
So if we wanted to get the last paragraph from that collection, we could do the following:
var paragraphs = d3.selectAll("p");
var lastParag = paragraphs[0].pop();
Or more concisely:
var obj = d3.select( d3.selectAll("p")[0].pop() );
"What about :last-child?"
The :last-child selector isn't the same as getting the last element on a page. This selector will give you the elements that are the last child of their parent container. Consider the following markup:
<div id="foo">
<p>Hello</p>
<p>World</p>
<div>English</div>
</div>
<div id="bar">
<p>Oie</p>
<p>Mundo</p>
<div>Portuguese</div>
</div>
In this example, running d3.select("p:last-child") won't return any of your paragraphs. Even d3.selectAll("p:last-child") won't. Neither of those containers have a last child that is a paragraph (they are <div> elements: <div>English</div> and <div>Portuguese</div>).
If you want to get the first DOM element from the D3's selection, use .node() method:
var sel = d3.selectAll('p'); // all <P>, wrapped with D3.selection
var el = sel.node(); // the first <P> element

Categories