Is there a way to get an element by its content(a word it contains?)
For example, get all the elements with the letter "F," and put it in a array of elements
I highly recommand you to use jQuery for these kind of DOM elements searching.
Then you can use this:
var foos = $("div:contains('foo')" )
will make an array with all divs containing the word 'foo'.
One fairly easy way is to select the elements you're interested in and then use 'filter' to look at the innerText. You can make this case insensitive with toLowerCase
var result = $('div').filter( (i,e) => e.innerText.toLowerCase().indexOf("f")>-1);
console.log("Items with 'F':",result.length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Forest</div>
<div>Fortnight</div>
<div>Trees</div>
<div>Africa</div>
The simpler way is using :contains('F') as a selector - but that is always case sensitive (which may be fine for your case).
You can use :contains as a selector. For example, to filter all divs of a special class that also contains your text, you can use $("div.myclass:contains('searched text')")
I think you can "bruteforce" it by iterating all DOM items. e.g.:
let arrayDom = Array.from(document.getElementsByTagName("*"));
arrayDom.forEach(element => {
if (element.innerHTML.contains('F')){
// Do something
}
})
Related
I'm trying to get all elements with id feed_item_{n} where {n} can be any integer greater than 0.
I know that I can use document.querySelectorAll('[id^="feed_item_"]') but that doesn't really help because I get also elements with these ids: feed_item_0_x, feed_item_x_0 where x may be any string
Is there a quick way to achieve that in one single line rather than running over all the elements I got from previous command and filttering them?
Since it's not possible to use RegEx within attribute selectors, the only way is to filter your querySelectorAll result; and there.. you can use a regex to match only numbers after feed_item_
It will be something like this
let items = [...document.querySelectorAll('[id^="feed_item_"]')].filter(
(item) => item.id.match(/\d+$/)
);
You also can use :not attribute, to get items whose id doesn't have _x by :not([id*="_x"]
const items = document.querySelectorAll('[id^="feed_item_"]:not([id*="_x"])')
console.log([...items])
<div id="feed_item_1">feed_item_1</div>
<div id="feed_item_2">feed_item_2</div>
<div id="feed_item_x_1">feed_item_x_1</div>
<div id="feed_item_1_x">feed_item_1_x</div>
Given a jQuery collection like this $(selector,containerElement), is it possible to test if a given Element will be part of that collection without constructing the collection at all.
That is, without doing this: $(selector,containerElement).is(someElement), which will construct a jQuery object with all the matched elements inside and then check if one of those elements is someElement.
Is there a more efficient way of doing it?
PS: Keep in mid that jQuery supports additional selector syntax like :has(), :lt(), :first and relative selectors like > tagName, + tagName.
I ended up implementing my own custom solution for this.
The following function does the trick.
function jQueryMatch(selector, container, element){
let attrName = '_dummy_876278983232' ;
let attrValue = (''+Math.random()).slice(2) ;
$(container).attr(attrName,attrValue) ;
selector = selector.replace(/(,|^)(\s*[>~+])/g,`$1 [${attrName}=${attrValue}]$2`) ;
return $(element).is(selector) ;
}
jQueryMatch(selector, container, element) is equivalent to $(selector, container).is(element).
I measured jQueryMatch to be between 3 and 10 times faster depending on the complexity of the selector. On bigger DOM trees, the difference will be even greater.
The function is super simple so it's easy to figure out what it does.
$.contains(containerElement, someElement);
If performance is an issue, you could use vanilla JS for this, such as:
[...yourContainer.querySelectorAll('yourSelector')].includes(elementToTest)
Sample:
let container = document.querySelector('[data-container');
let insideElement = container.querySelector('[data-inside-element]');
let outsideElement = container.querySelector('[data-outside-element]');
console.log([...container.querySelectorAll('[data-inside-element]')].includes(insideElement));
console.log([...container.querySelectorAll('[data-inside-element]')].includes(outsideElement));
<div data-container>
<p data-inside-element>element1</p>
<p data-inside-element>element2</p>
<p data-inside-element>element3</p>
</div>
<p data-outside-element>outside element</p>
Expanding on Brian Reynolds's answer:
$.contains(containerElement, someElement) && someElement.is(selector)
However, this won't work if selector starts with operators like >, +, or ~ that require it to be in a specific position relative to containerElement, since we've separated those variables.
Is there a way to do a wildcard element name match using querySelector or querySelectorAll?
The XML document I'm trying to parse is basically a flat list of properties
I need to find elements that have certain strings in their names.
I see support for wildcards in attribute queries but not for the elements themselves.
Any solution except going back to using the apparently deprecated XPath (IE9 dropped it) is acceptable.
[id^='someId'] will match all ids starting with someId.
[id$='someId'] will match all ids ending with someId.
[id*='someId'] will match all ids containing someId.
If you're looking for the name attribute just substitute id with name.
If you're talking about the tag name of the element I don't believe there is a way using querySelector
I was messing/musing on one-liners involving querySelector() & ended up here, & have a possible answer to the OP question using tag names & querySelector(), with credits to #JaredMcAteer for answering MY question, aka have RegEx-like matches with querySelector() in vanilla Javascript
Hoping the following will be useful & fit the OP's needs or everyone else's:
// basically, of before:
var youtubeDiv = document.querySelector('iframe[src="http://www.youtube.com/embed/Jk5lTqQzoKA"]')
// after
var youtubeDiv = document.querySelector('iframe[src^="http://www.youtube.com"]');
// or even, for my needs
var youtubeDiv = document.querySelector('iframe[src*="youtube"]');
Then, we can, for example, get the src stuff, etc ...
console.log(youtubeDiv.src);
//> "http://www.youtube.com/embed/Jk5lTqQzoKA"
console.debug(youtubeDiv);
//> (...)
Set the tagName as an explicit attribute:
for(var i=0,els=document.querySelectorAll('*'); i<els.length;
els[i].setAttribute('tagName',els[i++].tagName) );
I needed this myself, for an XML Document, with Nested Tags ending in _Sequence. See JaredMcAteer answer for more details.
document.querySelectorAll('[tagName$="_Sequence"]')
I didn't say it would be pretty :)
PS: I would recommend to use tag_name over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.
I just wrote this short script; seems to work.
/**
* Find all the elements with a tagName that matches.
* #param {RegExp} regEx regular expression to match against tagName
* #returns {Array} elements in the DOM that match
*/
function getAllTagMatches(regEx) {
return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) {
return el.tagName.match(regEx);
});
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"
i'm looking for regex + not + multiClass selector, and this is what I got.
Hope this help someone looking for same thing!
// contain abc class
"div[class*='abc']"
// contain exact abc class
"div[class~='abc']"
// contain exact abc & def(case-insensitively)
"div[class~='abc'][class*='DeF'i]"
// contain exact abc but not def(case-insensitively)
"div[class~='abc']:not([class*='DeF'i])"
css selector doc: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
simple test: https://codepen.io/BIgiCrab/pen/BadjbZe
I liked many of the answers above, but I prefer my queries run only on classes/IDs so they don't have to iterate over every element. This is a combination of code from both #bigiCrab and #JaredMcAteer
// class exactly matches abc
const exactAbc = document.querySelectorAll("[class='abc']")
// class begins with abc
const startsAbc = document.querySelectorAll("[class^='abc']")
// class contains abc
const containsAbc = document.querySelectorAll("[class*='abc']")
// class contains white-space separated word exactly matching abc
const wordAbc = document.querySelectorAll("[class~='abc']")
// class ends with abc
const endsAbc = document.querySelectorAll("[class$='abc']")
Substitute "class" with "id" or "href" to get other matches. Read the article linked below for further examples.
Reference:
CSS attribute selectors on MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
There is a way by saying what is is not. Just make the not something it never will be. A good css selector reference:
https://www.w3schools.com/cssref/css_selectors.asp which shows the :not selector as follows:
:not(selector) :not(p) Selects every element that is not a <p> element
Here is an example: a div followed by something (anything but a z tag)
div > :not(z){
border:1px solid pink;
}
Right now I have a dynamic string that assigns it's values to a particular div class.
Output looks like this
<div class="12923"></div>
I want to find that 'randNumber' div, then check if it has another class 'x'
Currently what I have now doesn't work:
var randNumber = 12923
var lookingForYou = $$('.'+randNumber);
if (lookingForYou.hasClass('XCLASS')){alert('XCLASS FOUND!');}
$$ returns an Elements instance, Elements is an array-like Class
anyway since you are basically filtering, you can tell Slick that you need an element with both class:
var randNumber = 12923;
if($$('.' + randNumber +'.XCLASS').length>0){
alert('XCLASS FOUND');
}else{
//dostuff
}
or you could just use one of the Elements methods, I think .some will be your best choice here:
var randNumber = 12923
var lookingForYou = $$('.' + randNumber);
alert(lookingForYou.some(function(el){
return el.hasClass('XCLASS');
}))
EDIT:
adding some links:
A better way to use Elements on MooTools blog
in my second example I used the some method, which, by looking at the source is not overloaded, but is just the one in Array.prototype.some:
Element.js source reference
Array.some on MDN
$$ returns an array of all matching elems. Not sure if you can do a hasclass on an array. Might have to do a .each() then do it. Try $('body').getElement('.'+randNumber).hasClass('XCLASS') this way you grab 1 elem if you don't want to mess with the array.
Here:
if (lookingForYou.hasClass('XCLASS')){alert('XCLASS FOUND!');}
$$() returns an array, and hasClass() performs the check on each element of the array, returning an array of booleans. Unfortunately, when you check if (...), then the return array, even if all of the values are false, is evaluated as true because it's non-empty.
Is there a way to do a wildcard element name match using querySelector or querySelectorAll?
The XML document I'm trying to parse is basically a flat list of properties
I need to find elements that have certain strings in their names.
I see support for wildcards in attribute queries but not for the elements themselves.
Any solution except going back to using the apparently deprecated XPath (IE9 dropped it) is acceptable.
[id^='someId'] will match all ids starting with someId.
[id$='someId'] will match all ids ending with someId.
[id*='someId'] will match all ids containing someId.
If you're looking for the name attribute just substitute id with name.
If you're talking about the tag name of the element I don't believe there is a way using querySelector
I was messing/musing on one-liners involving querySelector() & ended up here, & have a possible answer to the OP question using tag names & querySelector(), with credits to #JaredMcAteer for answering MY question, aka have RegEx-like matches with querySelector() in vanilla Javascript
Hoping the following will be useful & fit the OP's needs or everyone else's:
// basically, of before:
var youtubeDiv = document.querySelector('iframe[src="http://www.youtube.com/embed/Jk5lTqQzoKA"]')
// after
var youtubeDiv = document.querySelector('iframe[src^="http://www.youtube.com"]');
// or even, for my needs
var youtubeDiv = document.querySelector('iframe[src*="youtube"]');
Then, we can, for example, get the src stuff, etc ...
console.log(youtubeDiv.src);
//> "http://www.youtube.com/embed/Jk5lTqQzoKA"
console.debug(youtubeDiv);
//> (...)
Set the tagName as an explicit attribute:
for(var i=0,els=document.querySelectorAll('*'); i<els.length;
els[i].setAttribute('tagName',els[i++].tagName) );
I needed this myself, for an XML Document, with Nested Tags ending in _Sequence. See JaredMcAteer answer for more details.
document.querySelectorAll('[tagName$="_Sequence"]')
I didn't say it would be pretty :)
PS: I would recommend to use tag_name over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.
I just wrote this short script; seems to work.
/**
* Find all the elements with a tagName that matches.
* #param {RegExp} regEx regular expression to match against tagName
* #returns {Array} elements in the DOM that match
*/
function getAllTagMatches(regEx) {
return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) {
return el.tagName.match(regEx);
});
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"
i'm looking for regex + not + multiClass selector, and this is what I got.
Hope this help someone looking for same thing!
// contain abc class
"div[class*='abc']"
// contain exact abc class
"div[class~='abc']"
// contain exact abc & def(case-insensitively)
"div[class~='abc'][class*='DeF'i]"
// contain exact abc but not def(case-insensitively)
"div[class~='abc']:not([class*='DeF'i])"
css selector doc: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
simple test: https://codepen.io/BIgiCrab/pen/BadjbZe
I liked many of the answers above, but I prefer my queries run only on classes/IDs so they don't have to iterate over every element. This is a combination of code from both #bigiCrab and #JaredMcAteer
// class exactly matches abc
const exactAbc = document.querySelectorAll("[class='abc']")
// class begins with abc
const startsAbc = document.querySelectorAll("[class^='abc']")
// class contains abc
const containsAbc = document.querySelectorAll("[class*='abc']")
// class contains white-space separated word exactly matching abc
const wordAbc = document.querySelectorAll("[class~='abc']")
// class ends with abc
const endsAbc = document.querySelectorAll("[class$='abc']")
Substitute "class" with "id" or "href" to get other matches. Read the article linked below for further examples.
Reference:
CSS attribute selectors on MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
There is a way by saying what is is not. Just make the not something it never will be. A good css selector reference:
https://www.w3schools.com/cssref/css_selectors.asp which shows the :not selector as follows:
:not(selector) :not(p) Selects every element that is not a <p> element
Here is an example: a div followed by something (anything but a z tag)
div > :not(z){
border:1px solid pink;
}