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
Related
I have the following piece of HTML.
<div id="outer"><b class="dest">something</b>
<div id="test"><b class="dest">unwanted stuff</b></div>
</div>
Let's say I already have a reference to the outer element with document.querySelector("#outer"). How can I query all b elements with the dest class and are the first child of its parent? I tried document.querySelector("#outer").querySelector("b.dest") and document.querySelector("#outer").querySelector("b.dest:first-child") but only the first b element has returned. How can I get both b elements (through the result of document.querySelector("#outer"))?
.querySelector only selects one element max.
.querySelectorAll Returns an array-like node list.
You want:
var bElements = document.getElementById("outer").querySelectorAll('b.dest:first-child');
This will return an array of all elements that:
Have a parent with an id of outer
have the class dest
are the first-child of their parent
Then you can access each element just like an array, ex.
bElements[0]
DEMO:
var bElements = document.getElementById("outer").querySelectorAll('b.dest:first-child');
console.log(bElements)
<div id="outer"><b class="dest">something</b>
<div id="test"><b class="dest">unwanted stuff</b></div>
</div>
I'm writing a function for swapping the position of child elements in a parent element.
<div class="parent">
<div class="first-child"></div>
<div class="second-child"></div>
</div>
So I'm getting the children of .parent turning the Nodelist into an array, reordering the array to swap the order / position of the elements i.e first-child, second-child becomes second-child, first-child - This all works perfectly. However, ideally the function will return the parent element with the reordered structure, but because I effectively spliced the nodelist into an array the elements in the array are no longer considered 'nodes' meaning I get an error when attempting to append it as a child to the parent.
So, how can I convert an array of elements back into a Nodelist as I understand that a Nodelist is not native to javascript?
Here's a Codepen of what I have so far. http://codepen.io/anon/pen/QNPKqB?editors=0011
Thanks!
The error in your code isn't that you need a NodeList, it's that you've named both a function and an element swap.
var parent = document.querySelector('.swap');
swap(parent, first, second);
Is what you need
I don't have a codepen account so instead, see the working code here:
https://jsfiddle.net/owr15hnf/
This is how you can convert HTML to node list,
const targetElement = document.getElementById('targetElement');
const htmlElementsArray = Array.from(targetElement.children).map(el => el.outerHTML)
// htmlElementsArray contains an array of HTML Elements.
console.log(htmlElementsArray,'ArrayList.')
const nodeList = new DOMParser().parseFromString([htmlElementsArray].join(''), "text/html").body.childNodes;
// nodeList is the converted Html list to node list
console.log(nodeList,'nodeList')
You can find the example here: https://codepen.io/furki911/pen/qByzdXm?editors=1111
I had a situation in which I wanted to focus either an input tag, if it existed, or it's container if it didn't. So I thought of an intelligent way of doing it:
document.querySelector('.container input, .container').focus();
Funny, though, querySelector always returns the .container element.
I started to investigate and came out that, no matter the order in which the different selectors are put, querySelector always returns the same element.
For example:
var elem1 = document.querySelector('p, div, pre');
var elem2 = document.querySelector('pre, div, p');
elem1 === elem2; // true
elem1.tagName; // "P".
My question is: What are the "reasons" of this behavior and what "rules" (if any) make P elements have priority over DIV and PRE elements.
Note: In the situation mentioned above, I came out with a less-elegant but functional solution:
(document.querySelector('.container input') ||
document.querySelector('.container') ).focus();
document.querySelector returns only the first element matched, starting from the first element in the markup. As written on MDN:
Returns the first element within the document (using depth-first
pre-order traversal of the document's nodes|by first element in
document markup and iterating through sequential nodes by order of
amount of child nodes) that matches the specified group of selectors.
If you want all elements to match the query, use document.querySelectorAll (docs), i.e. document.querySelectorAll('pre, div, p'). This returns an array of the matched elements.
The official document says that,
Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors.
So that means, in your first case .container is the parent element so that it would be matched first and returned. And in your second case, the paragraph should be the first element in the document while comparing with the other pre and div. So it was returned.
That's precisely the intended behavior of .querySelector() — it finds all the elements in the document that match your query, and then returns the first one.
That's not "the first one you listed", it's "the first one in the document".
This works, essentially, like a CSS selector. The selectors p, div, pre and pre, div, p are identical; they both match three different types of element. So the reason elem1.tagName == 'P' is simply that you have a <p> on the page before any <pre> or <div> tags.
You can try selecting all elements with document.querySelectorAll("p.a, p.b") as shown in the example below and using a loop to focus on all elements that are found.
<html>
<body>
<p class="a">element 1</p>
<p class="b">element 2</p>
<script>
var list=document.querySelectorAll("p.a, p.b");
for (let i = 0; i < list.length; i++) {
list[i].style.backgroundColor = "red";
}
</script>
</body>
</html>
HTML
<div id="board">
<div>ab X</div>
<div>a <span class='target'>V</span> b</div>
<div>Xab</div>
<div>
I wanted to access the DOM place of V in my HTML and alert V, I must not use $('#board').eq(1).text().charAt(2). I need its DOM position so that I can easily trace the span that is wrapping the V.
THIS is not working, What's the right way?
alert($('#board').eq(1).eq(2).text());
This is the original problem, i can get someone who can help me so im trying to revised it How will i get the span class id under which the text belongs?
ALGORTIHM:
1. Found V from row looping and y looping
2. Find the span where it belongs to
Assuming span elements that have V text content should be selected, you can use .filter() method:
var $span = $('#board span').filter(function() {
return (this.textContent || this.innerText) === 'V';
});
Getting index of selected element:
$span.index();
Index of the V character within the text content of span's parent element:
var vIndex = $span.parent().text().indexOf('V');
Note that jQuery returns a jQuery-wrapped array of the selected elements, as you are using ID selector, the returned collection has only one wrapper/top-level selected element:
Object[div#board]
.eq(1)(just like getting an element by index from a simple array) returns the second top-level selected element that doesn't exist in the collection. Apart from that chaining .eq() methods in that way doesn't make any sense as it returns only one 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?