I have a series of div elements, some of which contains h2 element as children (direct or indirect (descendant)). I look for a javascript or jquery to give me the index of such a div element. Moreover I want to start the search from a specific div element. I mean a div element with an index greater than x containing h2. The following code find the ones in the series of all divs containing h2. However, some of divs may not contain h2 and should be counted.
$(".myDivs h2:gt(2)").eq(0)
Html example:
<div class='myDivs'></div>
<div class='myDivs'><h2>Hi</h2></div>
<div class='myDivs'></div>
<div class='myDivs'><div><h2>How are you</h2></div></div>
<div class='myDivs'></div>
if x=2 I want the index of 3 for the fourth div with class myDivs containing an h2.
This is what I found so far, which works:
$(".myDivs:gt("+x+"):has(h2)").eq(0).index()
Since gt is deprecated, the better solution is:
$(".myDivs").slice(x).has("h2").first().index()
Basically, I think you want a jquery something like this:
$(start).find("div").find("h2").parent("div").index();
From the start element, find your divs, then find the h2 tags in the divs, then get the parent divs of the h2s, and then get the index.
You may need a .each (...) after .find("h2");
Related
I'm making a turn-based game in javascript. I want to move the player from div to div. I have put all those divs in a section and then into an array using queryselectorall. Now my problem is that I also have another divs who I want to use and I can't select them separately. Can anyone tell me how to select only some divs? I have seen something like section>div to differentiate them, but that doesn't work for me.
I have tried replacing div with span on rollDice, zar1, and zar2, but by doing that some CSS breaks.
~
<div class="rollDice">Roll the dice</div>
<div class="zar1">
<img src="poze/dice-5.png" alt="Dice" class="dice" id="dice-1" style="width:150px">
</div>
<div class="zar2">
<img src="poze/dice-5.png" alt="Dice" class="dice2" id="dice-2" style="width:150px">
</div>
<section class="mutari">
<div class="nr1 mutabil"><h1>1</h1></div>
<div class="nr2 mutabil"><h1>2</h1></div>
<div class="nr3 mutabil"><h1>3</h1></div>
</section>
~
I want to select the div only from the section. And after that I want to select the first 3 divs.
What you are looking for is:
document.querySelectorAll('section > div:nth-child(-n+3)')
section (a type selector) finds your <section>. If you had more section elements, you could use section.mutari to be more precise (using a class selector).
> div selects all the <div> tags that are direct children of that section. > is a child combinator.
:nth-child(-n+3), a pseudo-class, restricts this to only select the first three elements, not all of them. It is not needed in your example, as you only have three divs; but if you had more, this would give you only the first three.
With document.body.childNodes
Just replace document.body with your HTML Element.
You can filter after that through the list you get an select all divs.
If you want to get all divs you can also use following:
var dh = document.body.getElementsByTagName('div');
Get all div nodes:
Use document.body.getElementsByTagName('div')
Or
Get filtered div nodes:
Take array from document.body.childNodes.
filter by using for loop and if condition.
Condition Example: use like node[i].nodeName and node[i].id
I have a problem with clone().
<div id="container">
<p id="template">a</p>
</div>
<script>
$(document).ready(function() {
$('#template').clone(true, true).appendTo('#container');
console.log($('#container').length); // it return 1, it supposed to return 2 right?, original and the cloned one.
});
</script>
The length of the container after the clone is 1, why not 2?
I checked via:
console.log($('#container').eq(1));
It returns undefined.
Shouldn't the cloned element become index number 1?
Because you are counting the number of element #container what you should count is the number of element inside of the container.
Appending in jquery means putting an element inside the #container.
calculate children's of container
console.log($('#container').children(".watever-class").length);
$('#container') is looking at the div called container. Since you're only looking at one div, the length of $('#container') is 1.
If you only want to count the number of paragraph elements inside the container, you can use this:
console.log($('#container p').length);
If you want to count the number of elements (not just paragraphs), you can use the children() function:
console.log($('#container').children().length);
Here's a JSFiddle that shows the different options and has comments explaining the three lines of code: https://jsfiddle.net/0uzusuwz/
I run into this problem frequently and never know the best approach. Imagine I have a structure that includes several instances of the following html:
<div class="known">
<div class="another unknown">
<div class="unknown">
<h4>Something a something</H4>
</div>
</div>
</div>
For each div of class known, I want to change the inner html of that div only if it contains a div inside it with some particular tag, in this case <h4>.
What is the best way to achieve that. I know that I could do it by taking the inner html of class known and doing a regex match. But is there a more robust way based on tags?
Simple, just use a selector that spans over the div.known and restrict it's context to div h4. If the selector selects at lease one element then the div.class has children as you expect.
if( $('.known div h4').length > 0 ){
$('.known').html('Some html');
}
Yes! You can do this.
var head = Array.prototype.slice.call(document.querySelectorAll("h4 #known"));
for(var i = 0; i < head.length; i++)
{
while(head[i].className !== "known")
head[i] = head[i].parent();
}
Now head will be an array of all the DOM elements have the tag known and have h4's in them.
With jQuery, you can use .has() to narrow your selection and even chain other methods, as in:
$(".known").has("h4").css("background","red");
Check out this fiddle for example. Notice that clicking the button will change the color of any div.known only if that element contains an h4 tag as a descendant.
Documentation on jQuery's .has() -- https://api.jquery.com/has/
I have read this question and its answer, and wish to take it a little bit further.
I want to use CasperJS.click(selector) function to click multiple links matching a selector. Please note that the links do not have a significant href tag.
Consider the following markup:
HTML:
<div>
<h1 class='myLink'>Cocacola</h1>
<div>
<div>
<h1 class='myLink'>Sprite</h1>
</div>
</div>
</div>
The answers I've mentioned on top here suggest deleting the links so we can click the remaining elements with casper.exists and so on. What if I don't want to manipulate the page?
For reasons beyond my conception, using:
document.querySelector("div .myLink:nth-of-type(1)");
catches the first h1, Cocacola. But:
document.querySelector("div .myLink:nth-of-type(2)");
returns null.
Fiddle here.
Any ideas? Many thanks!
CSS spec for :nth-of-type says that:
The :nth-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent element.
That is, the elements will have to be siblings.
For example,
<div>
<h1 class='myLink'>Cocacola</h1>
<h1 class='myLink'>Miranda</h1>
<div>
<div>
<h1 class='myLink'>Sprite</h1>
</div>
</div>
</div>
The selector div .myLink:nth-of-type(2) will select Miranda. That is, given n siblings of type 'div .myLink', the selector will select the second element from them.
Here is the fiddle for the above example.
Hope this helps!
As mentioned, the reason :nth-of-type(1) works but :nth-of-type(2) doesn't is because there is only exactly one h1 of each type as a child of its parent div. The class selector .myLink is a separate condition entirely and does not affect how :nth-of-type() works.
The reason your first statement appears to return the first element, even though there are technically two elements matching :nth-of-type(1), is because querySelector() returns only the first match.
To obtain the first and second elements matching your selector, use querySelectorAll() instead of querySelector(), and an indexer instead of the :nth-of-type() pseudo-class:
var cocacola = document.querySelectorAll("div .myLink")[0];
var sprite = document.querySelectorAll("div .myLink")[1];
I want to be able to refer to any element within an HTML DOM and also know what order the elements appear in. I'm hoping elements in the DOM get indexed somewhere from 0 to <number-of-elements-minus-1> so that I can identify specific elements and, separately, list those elements in the order they appear within the HTML.
For example, in this HTML, the elements would be numbered from 0 for the html element, to 9 for the second p element:
<html lang="en-US">
<head>
<title>Element 2. Page title</title>
</head>
<body>
<h1 id="mainHead">Element 4. How to uniquely identify/order DOM elements</h1>
<div id="boxedContent">
<p class="smallText">Element 6. I want to be able to <span class="stress">7. uniquely</span> identify each element and <i>8. also</i> determine the order in which elements appear, reading from top to bottom through the HTML.</p>
</div>
<p>Element 9</p>
</body>
</html>
I want a JavaScript/jQuery way of specifying, for example, the title element, first p element and the span. The HTML pages I'll be working with aren't mine, but if there's a whole-DOM element index that I can access I could get to these 3 elements using those index refs - i.e.
title: 2
first p: 6
span: 7
The index numbers would allow me to list the elements in order.
Is this possible? How do I do it?
A better option would be to use node.compareDocumentPosition(node) (no jQuery needed)
see: https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
Given a list of nodes you can sort them this way:
nodes.sort((a, b) =>
a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1
);
You could do something like this:
var elems = document.getElementsByTagName('*');
This will create an array-like object of all DOM element.
Then, there are many ways you can get the index of a specific element in that array-like object.
You could do this:
var indexOfTitle = elems.indexOf(document.getElementsByTagName('TITLE'));
Or, you can create a for loop which loops through all the elements in the elems variable, and uses a property like tagName to find it, etc.