Does querySelectorAll support the period(.) character in an id? - javascript

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.

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 do you add an element to a class (through JavaScript)?

Suppose that I want to add a newly created paragraph (using document.createElement("p")) into an existing div (with class name "container") in one of my html files. Is there a way to do this by calling some methods?
Since there's a getElementById() method, I figured I would use a getElementByClassName() method too, but that doesn't exist; what exists is getElementsByClassName() instead. One way I can get around this is to just change my div to have an id rather than a class name, and use the getElementById() to add the paragraph into the div, but I wanted to know if there was some method that I could call that would help me retrieve a class element (rather than the elements within the class itself).
I've tried looking for this online, but what I've found are answers to "how to add class names to elements" instead, which is not what I want to know.
For one element, this will chose first in DOM order:
var p = document.createElement("p");
p.innerHTML = "p element";
document.querySelector(".container").appendChild(p);
<div class="container">container</div>
For all elements with chosen class:
[...document.querySelectorAll('.container')].forEach(el => {
var p = document.createElement("p");
p.innerHTML = "p element";
el.appendChild(p);
})
<div class="container">container</div>
<div class="container">container2</div>
HTML DOM elements' IDs have to be unique within a document - and so asking for an element by Id will return you just one element (or null if there isn't a matching element).
However a class name can be applied to multiple elements, so you would expect to get zero one or more elements when searching by class, hence the getElementsByClassName returns a collection.
So if you have a list of elements with the class name container, and you know your document (hopefully) only contains one element with that name, you can pick the first element returned by the getElementsByClassName - e.g. getElementsByClassName('container')[0]
Note - getElementsByClassName returns all elements to which the class has been directly applied, for the children of the element on which it is being called. I've interpreted your query as relating to the whole document in the context of your original question.

How to change class style for children element by parent element id?

For example I have simple html code:
<a id="news" href="#"><div class="" >News</div></a>
How to change class style for div element by id of href on pure javascript ?
Or may be better describe div properties in class for "a" element ? ( How to do it ?)
You can get a reference to your "news" element using getElementById. Then you can find the div in its childNodes and set the div's className property.
For instance, this would work with the HTML you've quoted to set the "foo" class on the element:
document.getElementById("news").childNodes[0].className = "foo";
...because the div is the first child of the "news" element. Or if you want to add the "foo" class:
document.getElementById("news").childNodes[0].className += " foo";
Also worth looking at querySelector and querySelectorAll, which are supported by most (but not all) browsers currently in use (more on support).
If you might have other elements, whitespace/text nodes, etc., you might look at getElementsByTagName rather than childNodes so you only get the specific elements you're interested in:
document.getElementById("news").getElementsByTagName('div')[0].className += " foo";
More to explore:
DOM3 Core specification
DOM2 HTML specification
Selectors API specification
HTML5 Web Applications API
There are a number of ways to do it but assuming the direct structure above.
var new_class = "ClassName";
document.querySelector('a#news > div').setAttribute('class', new_class);
Of course if your browser doesn't support querySelector you'll have to do a bit more finagling like this
document.getElementById('news').childNodes[0].setAttribute( 'class', new_class );
var newsA = document.getElementById('news');
var myDiv = newsA.getElementsByTagName('div')[0];
myDiv.setAttribute('class', 'myClass');
That is one way.
To turn that into one nice line of code:
document.getElementById('news').getElementsByTagName('div')[0].setAttribute('class', 'myClass');
As in HTML5, it is better to use dataset modifiers, like this:
.some-content[data-alt = "white"] {
background: white;
}
and then in javascript:
someElement.dataset.alt = "white"

how to append a css class to an element by javascript?

Suppose a HTML element's id is known, so the element can be refereced using:
document.getElementById(element_id);
Does a native Javascript function exist that can be used to append a CSS class to that element?
var element = document.getElementById(element_id);
element.className += " " + newClassName;
VoilĂ . This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).
Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.
In prototype, for instance:
// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);
See how much nicer that is?!
Adding class using element's classList property:
element.classList.add('my-class-name');
Removing:
element.classList.remove('my-class-name');
classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.
Not supported in IE < 10
When an element already has a class name defined, its influence on the element is tied to its position in the string of class names.
Later classes override earlier ones, if there is a conflict.
Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.
document.addClass= function(el, css){
var tem, C= el.className.split(/\s+/), A=[];
while(C.length){
tem= C.shift();
if(tem && tem!= css) A[A.length]= tem;
}
A[A.length]= css;
return el.className= A.join(' ');
}
You should be able to set the className property of the element. You could do a += to append it.
addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));
This will add ONE class or MULTIPLE classes :
addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"
you could use setAttribute.
Example:
For adding one class:
document.getElementById('main').setAttribute("class","classOne");
For multiple classes:
document.getElementById('main').setAttribute("class", "classOne classTwo");

Categories

Resources