Is there a way to grab an element by attribute? - javascript

I have the following custom tag/directive :
<tile class="ng-scope gridster-item" tilevalue="1" gridster-item="tile" row="0" col = "0" ng-repeat="tile in selectedTiles"> </tile>
I wanted to set focus on this element. Is there a way to get an element by attribute name, so that I can set focus?

With plain javavascript you can use .querySelector and .querySelectorAll to get the elements you want, just like in CSS.
var element = document.querySelector('[class="ng-scope gridster-item"]')
var element = document.querySelector('[gridster-item="tile"]')
Then you are free to use whatever you want with element.

as you tagged jquery, you have a lot of possibility, if there is only one element named "tile", you can use the element name $("tile"), or $(".ng-scope.gridster-item") based on classes.
Otherwise, use any attribute with $("[attribute_name='attribute_value']")
Note this can return an array of object. To get the element itself use $("[attribute_name='attribute_value']")[0] for example.

Use document.querySelector or document.querySelectorAll (no jQuery required)
var elements = document.querySelectorAll("[gridster-item]");
or:
var elements = document.querySelectorAll("[gridster-item=tile]");
Set the focus:
elements[0].focus();
querySelector returns the first element, querySelectorAll returns an array-like NodeList.

Related

How do I select a DOM element that has multiple classes?

I am trying to select a DOM element that has these classes:
mq-editable-field mq-math-mode mq-field
I have tried using:
document.getElementsByClassName('mq-editable-field mq-math-mode mq-focused')
This is not working, is there another document function I should be using? I am using vanilla javascript.
Use a query selector:
document.querySelector('.mq-editable-field.mq-math-mode.mq-focused')
you can use querySelector and querySelectorAll for get multiple-element by classes
querySelector method : return the first element within the document which matches a specified CSS selector(s)
let firstElement= document.querySelector('.mq-editable-field.mq-math-mode.mq-focused');
querySelectorAll() method : method returns all the elements within the document which matches the specified CSS selector(s).
let elements = document.querySelectorAll('.mq-editable-field.mq-math-mode.mq-focused');

Is there any way to use Dojo/query to grab classname with a specific number instead of getElementsByClassName

I wanted to change document.getElementsByClassName to dojo.query or query but wont' work:
var name = document.getElementsByClassName("dijitReset dijitInputInner")[1];
this one works
var name = dojo.query(".dijitReset dijitInputInner")[1];
this one won't work
.query returns an array-like NodeList, and getElementsByClassName returns an array-like HTMLCollection. The problem is not with that, but with your selectors.
document.getElementsByClassName("dijitReset dijitInputInner")
will select elements with either the class dijitReset or the class dijitInputInner.
dojo.query(".dijitReset dijitInputInner")
will select elements with a tag name of dijitInputInner that are descendants from an element with a class name containing dijitReset.
You need to change it to:
dojo.query(".dijitReset, .dijitInputInner")
with the comma (to indicate a new selector) and a . (to indicate a search for class).

How can you find an HTML element on a page purely by the number of characters in its id attribute JavaScript?

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);

How to assign to an HTML element without knowing id/class/tag in javascript?

I'm not talking about jquery at all, but with jquery, it's easy to work with object. Like this:
$(selector)
So, selector can be: a string (can contain id, class name, tag name, attribute...) or an object. I called it: wrap the selector by $().
Can I do same thing with javascript (document.get(selector))?
I've made a function which accepts an HTML object. I want to change the style of it.
Html:
<div></div>
Script:
var changeCSS = function (selector) {
// I DON'T WANT TO USE jQuery HERE
// these function doesn't work to target the object (I'd tried)
// because I'm not sure the selector has an id, class name... or not
// document.getElementById
// document.getElementsByClassName
// document.getElementsByName
// document.getElementsByTagName
// document.querySelector
// my goal looks like: (wrap the selector by 'get' function)
selector = document.get(selector);
selector.style.width = '100px';
selector.style.height = '100px';
};
let selector = $('div')[0]; // not contain id, class name...
changeCSS(selector);
In my project, changeCSS is a plugin, it doesn't require jquery before using. But I've used jquery in another place.
Totally, I want to know how can I convert (an HTML object, not a string)
<div></div>
to a selector?
Thank you!
The querySelector and querySelectorAll methods accept a string containing a selector and return an Element or non-live NodeList respectively.
You can call them on document or an element object.
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on
their name, id, classes, types, attributes, values of attributes and
much more. It's based on the existing CSS Selectors, and in addition,
it has some own custom selectors.
If you are trying to replicate the selector functionality of jQuery:
document.querySelector(.class or tag or #id);

How do you grab an element relative to an Element instance with a selector?

I am writing a small library where I am in need of selecting a relative element to the targeted element through querySelector method.
For example:
HTML
<div class="target"></div>
<div class="relative"></div>
<!-- querySelector will select only this .target element -->
<div class="target"></div>
<div class="relative"></div>
<div class="target"></div>
<div class="relative"></div>
JavaScript
var target = document.querySelectorAll('.target')[1];
// Something like this which doesn't work actually
var relativeElement = target.querySelector('this + .relative');
In the above example, I am trying to select the .relative class element relative only to the .target element whose value is stored in target variable. No styles should apply to the other .relative class elements.
PS: the selectors can vary. So, I can't use JavaScript's predefined methods like previousElementSibling or nextElementSibling.
I don't need solution in jQuery or other JavaScript libraries.
Well it should be ideally:
var relativeElement = target.querySelector('.relative');
But this will actually try to select something inside the target element.
therefore this would only work if your html structure is something like:
<div class="target">
<div class="relative"></div>
</div>
Your best bet would probably in this case be to use nextElementSibling which I understand is difficult for you to use.
You cannot.
If you insist on using the querySelector of the subject element, the answers is there is no way.
The spec and MDN both says clearly that Element.querySelector must return "a descendant of the element on which it is invoked", and the object element you want does not meet this limitation.
You must go up and use other elements, e.g. document.querySelector, if you want to break out.
You can always override Element.prototype.querySelector to do your biddings, including implementing your own CSS engine that select whatever element you want in whatever syntax you want.
I didn't mention this because you will be breaking the assumption of a very important function, easily breaking other libraries and even normal code, or at best slowing them down.
target.querySelector('.relative');
By using querySelector on the target instead of document, you scope the DOM traversal to the target element.
It is not entirely clear from your explanation, but by related i assume you mean descendant?
To get all target elements you can use
document.querySelectorAll('.target')
And then iterate the result
I found a way which will work for my library.
I will replace "this " in the querySelector with a unique custom attribute value. Something like this:
Element.prototype.customQuerySelector = function(selector){
// Adding a custom attribute to refer for selector
this.setAttribute('data-unique-id', '1');
// Replace "this " string with custom attribute's value
// You can also add a unique class name instead of adding custom attribute
selector = selector.replace("this ", '[data-unique-id="1"] ');
// Get the relative element
var relativeElement = document.querySelector(selector);
// After getting the relative element, the added custom attribute is useless
// So, remove it
this.removeAttribute('data-unique-id');
// return the fetched element
return relativeElement;
}
var element = document.querySelectorAll('.target')[1];
var targetElement = element.customQuerySelector('this + .relative');
// Now, do anything with the fetched relative element
targetElement.style.color = "red";
Working Fiddle

Categories

Resources