querySelector("#ID1, #ID2, ID#3")
Is there a possibility to put into one querySelector some IDs?
querySelectorAll can be used to target multiple selectors.
document.querySelectorAll("#div1, .div2, h3");
Simple ! Use following code.
document.querySelectorAll('#id1, #id2 , #id3');
This will return nodelist which you can iterate and can perform actions that you want.
The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
Keep in mind that to return all the matches, use the querySelectorAll() method instead.
example
<div class="bar">.first </div>
<div class="bar">.second</div>
//get the first element with class bar
let firstElement = document.querySelector('.bar');
//log the first match
console.log(firstElement)
//get all elements with class bar
let allElements = document.querySelectorAll('.bar')
//You can use any common looping statement to access the matches
allElements.forEach(function(elements){
console.log(elements);
});
/*
querySelector("#ID1, #ID2, ID#3")
*select element matches #ID1
*select element matches #ID2
*select element matches #ID3
**/
//select elements matches specified selectors #id1 , #id2 , #id3 and use any common looping statement to access them
let allMatchesId = document.querySelectorAll('#id1 , #id2 , #id3');
allMatchesId .forEach(function(elements){
console.log(elements);
});
read the docs here at MDN https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
const divs = document.querySelectorAll('#id1, #id2');
console.log(divs[0], divs[1]);
<div id="id1"><div id="id2"></div></div>
Source
Just some more explanation:
This will work (if you correct the error ID#3 instead of #ID3), however querySelector only returns the first element in the document that it matches (NOT the first ID in the list).
If you want all of the elements, then use querySelectorAll, but again the order of the elements will NOT be the order of the IDs, but the order of elements in the document. For example, given the following HTML:
<div id="id2"></div>
<div id="id1"></div>
then following JS:
const divs = document.querySelectorAll("#id1, #id2");
alert(divs[0].id); // This will show "id2"!
Related
The correct way to give an element multiple classes is simply put spaces between them. Right?
Then why does the selector [class=CLASSNAME] not work unless it's the only class?
[class^=CLASSNAME] works if the class is the first one.
But how to select all elements that possess a given class, regardless of the number or order of their classes?
I want to select all the elements with class foo-bar. But the code below only selects the first one.
const selector = '[class=foo-bar]';
const divs = document.querySelectorAll(selector);
console.log([...divs].map(div => div.textContent));
<div class="foo-bar">foo</div>
<div class="foo-bar baz">bar</div>
<div class="baz foo-bar">baz</div>
When you use an attribute selector, it's matching against the entire attribute value as an ordinary string. It doesn't treat the class attribute specially, so it's not considered to be a list of classes that can be matched individually.
Just as in CSS, use .classname to match any class in the list.
const selector = '.foo-bar';
const divs = document.querySelectorAll(selector);
console.log([...divs].map(div => div.textContent.trim()));
<div class="foo-bar">foo</div>
<div class="foo-bar baz">bar</div>
<div class="baz foo-bar">baz</div>
I want to use JavaScript to find a specific HTML element by the number of characters in its id attribute.
For example if the element I want to find looks like this:
<element id="12345678"></element>
And has 8 characters in its id attribute, how would I find this element.
Some basic pseudo code I imagine would look like this:
[e] = document.GetElementById where id.charLength == 8
And this would return an array with all elements on the page whose id attribute is 8 characters long.
In case anyone asks, I cannot just use the id to get the element because the id changes with every page refresh. Xpath will not work either as the element changes its position in the DOM with every refresh. There are no constant identifying attributes of the element's parents either.
The only constant is the length of the id attribute of this specific element, and so I have concluded that this is the only way to grab the element.
You could use Document.querySelectorAll() with an attribute selector to find all elements on the page that have an id attribute (with any value) and then use Array.prototype.filter() (and Array.from()) to filter them according to their id's length:
console.log(Array.from(document.querySelectorAll('[id]'))
.filter(element => element.id.length === 3));
console.log(Array.from(document.querySelectorAll('[id]'))
.filter(element => element.id.length === 6));
<div></div>
<div id="123"></div>
<div id="456"></div>
<div id="123456"></div>
<div id="987654"></div>
Here is the solution in pure xpath.
//element[string-length(#id)=8]
Try Javascript: How to loop through ALL DOM elements on a page? to loop through all elements and then set your own criteria (for the id length) during that loop
You can do first get all the dom elements by using document.getElementsByTagName("*") and then use find to get the required dom element
const domElements = document.getElementsByTagName("*");
const required = [...domElements].find(element => element.id.length === 8);
I have some <div>s where I want to append some data to a child div with a specific class but I'm not sure how to do that:
Here is my JS code:
let items = document.querySelectorAll(".item");
items.forEach(function (item) {
let textnode = document.createElement('p');
textnode.innerHTML = 'some text';
item.appendChild(textnode);
});
This actually works, bu it only appends the "textnode"-element to the existing elements.
When I try:
document.getElementsByClassName('left').appendChild(textnode);
It doesn't work.
Here is a JSFIDDLE
EDIT
I want to append the data to the .left element
It seems you want to append an element to .left descendant of item elements. If this is the case, you can use the querySelector instead of getElementsByClassName:
item.querySelector('.left').appendChild(textnode);
Note that above code calls the querySelector method as a member of item (instance of HTMLDivElement interface).
getElementsByClassName returns multiple elements. Class names are not unique. Therefore you first need to select an element in that list.
var textnode = document.createTextNode("Test");
var node = document.getElementsByClassName('left');
node[0].appendChild(textnode);
<div class="left"></div>
getElementsByClassName returns the array of elements. So u need to use the index for that.
let x = document.getElementsByClassName('left')
x[0].appendChild(textnode)
This is working.
I have updated the code in your fiddle. Please check out
Given HTML:
<div id="div-a"></div>
<div id="div-b"></div>
<div id="div-c"></div>
And a previously-created jQuery selection:
var $divs = $("div");
How can I select a particular div in that selection by its id?
Note: the $divs selection has not yet been appended to the DOM, so I can't just select directly (e.g. $("#div-b")).
find() selects descendants of a selection, so this does not work:
$divs.find("#div-b");
has() / :has() selects elements that contain an element with the specified selector, so this does not work:
$divs.has("#div-b");
You want to use filter() to reduce the set/.
var elem = $divs.filter("#div-b");
I think you are looking for filter():
var $subset = $divs.filter("#div-b");
If you want to only examine elements within a particular jQuery object that you've already created, you can use the .filter() method:
var $divs = $("div");
var item = $divs.filter("#div-a");
This will examine only the elements within the $divs jQuery object so see if any of them match the selector "#div-a" and will return to you a new jQuery object that contains only the matches (either zero or one object in this case).
How can i select only the first child of a particular class of a parent with a particular class for the purposes of clone()?
<div class="sector_order">
<div class="line_item_wrapper">
SELECT THIS DIV
</div>
<div class="line_item_wrapper">
NOT THIS DIV
</div>
</div>
I am trying like this:
var form1 = $(this)
.parents('.sector_order')
.children('.line_item_wrapper')
.children().clone(true)
and get both inner divs with the class line_item_wrapper, but I get an empty object when I try with this addition:
children('.line_item_wrapper :first')
Thanks!
Your problems is that your selector is wrong, in a few ways:
parents() returns one, two or many elements that match the selector passed to the method; to limit yourself to the first-matched element use closest() (which returns one, or no, elements that match the passed-in selector).
Your first use of the children() method returns both elements, since they both match the supplied selector and have the class of line_item_wrapper; you need to explicitly state which of the two you want, you can either use the :first selector (or the first() method), or the :first-child selector.
The second call to the children() method finds the children of the first element matched by the selector, which you don't seem to want.
Anyway, if you must use the parent (starting from the same $(this) element):
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper:first').clone(true);
Or:
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper').first().clone(true);
Or:
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper:first-child').clone(true);
Or, frankly, a simpler approach (but this does dispense with the parent class-name check):
var form1 = $(this).prevAll('.line_item_wrapper:last');
Or:
var form1 = $(this).siblings('.line_item_wrapper').eq(0);
References:
closest().
eq().
find().
:first.
:first-child.
first().
:last.
parents().
prevAll().
siblings().
You're passing an invalid selector to children().
Instead of
.children('.line_item_wrapper :first')
try
.children('.line_item_wrapper').first()
Use :first-child
var form1 = $(this).closest('.sector_order').find(':first-child');
OR .first()
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper').first();
Try this:
var $firstDiv = $(".sector_order > .line_item_wrapper:eq(0)");
This will get you the first direct descendant of sector_order with the class line_item_wrapper.
Example fiddle