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');
Related
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);
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.
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
What is the difference between two statements:
$("span[id$='id']").text(var);
// And
$("#id").text(var);
HTML code is : <span class="normal11" id="id"></span>
The first one is using ends with selector while the second one is using just normal id selector.
Attribute Ends With Selector [name$="value"]
ID Selector ("#id")
By the documentation on JQuery:
$("#id") uses the JavaScript function document.getElementById(), which is extremely efficient. Link.
So, the second way should be faster and should be used.
Some different between id selector and attribute selector is
Since id selector called document.getElementById(),
it only return the first element that have a id equal to that.
However, if you use attribute selector, it will return all elements that have the id attribute that equals to that.
But duplicated id is actually invalid in HTML, and should never used.
if you really want to do that, use class instead.
example
$("#id-selector").click(function(){
$("#test").css("color", "red");
});
$("#attr-selector").click(function(){
$("*[id=test]").css("color", "blue");
});
http://jsfiddle.net/toucyqas/1/
Does querySelectorAll support the period(.) character in an id?
I mean if I append an element like below:
var div = document.createElement('div');
div.id='my.divid';
document.body.appendChild(div);
and then I use querySelectorAll like below:
document.querySelectorAll('#my.divid');
then I get nothing!
So period is legal character for id, and querySelectorAll is the official method which Firefox provided; I can't believe the method doesn't support period(.) in id. Did I make some mistake?
You need to remember that . represents a class selector, so the selector #my.divid represents an element with the ID my and a class divid, not an element with the ID my.divid. So, the following element would be matched by your selector:
var div = document.createElement('div');
div.id = 'my';
div.className = 'divid';
document.body.appendChild(div);
If you need to select an element with the ID my.divid as you have given above, you need to escape the period:
document.querySelectorAll('#my\\.divid');
Note that the double backslash is because it's a JS selector string; in a CSS rule you would use a single backslash: #my\.divid
A period in querySelectorAll means you are specifying a css class. In your case querySelectorAll is trying to find out a DOM element with id "my" and having a css class "divid". How will querySelectorAll know that this time you want element by id and not by class? It is up to you to have proper id atrribute so as to no to confuse the method. Though a period is allowed, the best practise is to avoid it most of the time so that you do not confuse other libraries like jquery etc.