About getElementById find multiple id name? - javascript

I have three id tag
<div id="view_1"></div>
<div id="view_2"></div>
<div id="view_3"></div>
I use getElementsByClassName way it can work
but "class" I take it to delimit css style
How could use document.getElementById find -> "view_1" "view_2" "view_3"
function hideDIV(){
var divs = document.getElementById('view'.*);
for(var i=0; i<divs.length; i++) {
divs[i].style.display='none';
}
}

You can do this:
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++) {
if(divs[i].id.indexOf('view_') == 0) {
divs[i].style.display='none';
}
}
DEMO

Use QuerySelectorAll for that:
document.querySelectorAll('[id^="view_"]').id;
This will get all views that start with view_
See:
Javascript getElementById base on partial string

Try doing this : Fiddle
JS:
$('[id*="view"]').hide();
Html:
<div id="view_1"> dcf</div>
<div id="view_2"> DSg</div>
<div id="view_3"> gsde</div>

No, it won't work.
document.getElementById() method accepts only one argument.
However, you may always set classes to the elements and use getElementsByClassName() instead. Another option for modern browsers is to use querySelectorAll()method:
use $("div[id*='view']")
DEMO :http://jsfiddle.net/mkufymqr/1/

Vanilla JavaScript
document.querySelectorAll('div[id^="view_"]');
jQuery
$('div[id^="view_"]');
CSS 3
div[id^="view_"] { ... }
But consider using classes, not IDs, to semantically target elements.
Eg: search for all DIVs with the targetDiv class, and add the hidden class to them. Then define the hidden class as display: none in CSS.

Related

how to select tags that are inside certain other tags

I want to select all the <"a"> tags on a page that are inside all the <"code"> tags on the page so I can count them, and I want to do this using JavaScript.. how can I do this?
I tried using document.getElementsByTagName("code").getElementsByTagName("a"); and document.getElementsByTagName("code").querySelectorAll("a"); but it doesn t seem to work
document.getElementsByTagName("code").getElementsByTagName("a");
VM1278:1 Uncaught TypeError: document.getElementsByTagName(...).getElementsByTagName is not a function
at :1:39
You can use .querySelectorAll(selectors).
const matches = document.querySelectorAll('code a');
console.log(matches);
<code>
<a>Test</a>
<p>Other tag</p>
<a>Example</a>
</code>
You need to loop through the initial element search, since it returns an HTMLCollection of elements:
var elements = document.getElementsByTagName("code");
var all = [];
for(var i = 0; i < elements.length; i++){
var tempElements = elements[i].getElementsByTagName("a");
all = [...tempElements, ...all];
}
Try this instead:
document.querySelectorAll('code a').length
The querySelector and querySelectorAll functions accept CSS-like DOM selectors and return a node or NodeList, respectively.
See:
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
You can use
document.querySelector("code > a");
you can do it like this:
var anchors = document.getElementById("thediv").getElementsByTagName("a");
alert("The Div has " + anchors.length + " links in it");
<div id="thediv">
link 1
link 2
link 3
</div>

getElementById from ancestor element to remove child's class

I want to use a parent element with getElementById.
For example: I want to use ancestor id "test" to remove class "myClass".
HTML
<div id="test">
<div id="test-child-one">
...
</div>
<div id="test-child-two">
...
</div>
<div id="test-child-three">
<div class="myClass"></div>
</div>
</div>
Javascript
var element = document.getElementById("test");
element.className = element.className.replace(/\bmyClass\b/g, "");
It won't work. Please help! Thanks.
You could do this:
//If you want to remove the class from all decendants
//Get all decendants with class "myClass"
const childEles = document.getElementById('test').querySelectorAll('.myClass');
//Or per David
const childEles = document.querySelectorAll('#test .myClass');
//Iterate the collection and remove "myClass" from all decendants
for(let x = 0; x < childEles.length; x++){
childEles[x].classList.remove("myClass");
}
//If you only want to remove the first decendant
document.getElementById('test').querySelectorAll('.myClass')[0].classList.remove("myClass");
//Or per David
document.querySelectorAll('#test .myClass')[0].classList.remove("myClass);
Do like Ryan Wilson specified it or simple one-liner:
document.getElementById("test").querySelectorAll('.myClass').forEach(function (el) { el.classList.remove("myClass"); });
Or a beautiful way, if you have transpiler between your code and browser:
removeChildrenClass = (parentId, childClass) => document.querySelectorAll(`#${parentId} .${childClass}`).forEach(el => el.classList.remove(childClass));
removeChildrenClass("test", "myClass");
Expanding on the other answers provided, it seems as though you are looking for querySelectorAll. Given that you already have some ancestor element element, querySelectorAll can be used to find all children with the specified class. To build on your example:
Using querySelectorAll
// Example constant element IDs/classes
var parentId = "test";
var targetClass = "myClass";
// The given parent element
var element = document.getElementById(parentId);
// Iterate over all children `elem`s with the target class
element.querySelectorAll(targetClass).forEach(function (elem) {
elem.classList.remove(targetClass);
});
This is just an example to demonstrate how querySelectorAll can be used on specific elements to solve exactly such a problem. Note that querySelectorAll will match multiple classes containing myClass if they exist, if you want to specifically remove the first such class, you might use querySelector instead.

Apply .classList.add() to all divs that .startsWith("example") - No jQuery

I wish to do the following but am unsure on how to properly utilize the content targeted within .startsWith.
This is what I have:
var divClass = document.querySelector('div').getAttribute('class');
if (divClass.startsWith('example')){
divClass.classList.add('width', 'height');
}
as shown above, I have attempted to use classList.add() on divClass with no prevail. I believe this strategy is indeed incorrect, however, I believe something like the following is closer...
var divClass = document.querySelector('div').getAttribute('class');
if (divClass.startsWith("example")){
example.classList.add('width', 'height');
}
...Although I struggle to directly target example and use .classList.add() to apply classes to all divs with the example class.
If anyone has a solution to this It'd be greatly appreciated and I thank you in advance!
FYI - All solutions please be in Vanilla JavaScript (No jQuery)
You can use this selector getElementsByClassName
var list = document.getElementsByClassName("example");
for(var i=0;i<list.length;i++){
list[i].classList.add("mystyle");
}
for searching similar classes this solution works
var x = document.querySelectorAll('div');
var i;
for (i = 0; i < x.length; i++) {
if(x[i].classList.value.indexOf('example') > -1){
x[i].classList.add("mystyle");
}
}
Retrieve all the div with the classname starting with example and iterate over the node collection you've found
let divClass = document.querySelectorAll('div[class^="example"]');
[].forEach.call(divClass, function(div) {
/* do something on div */
});
querySelector only gets one element, so you are only selecting the first div on the page and working with that. To get a list of elements, use querySelectorAll.
In jQuery you're able to call $('div').addClass('example') and you don't have to care whether there is one div or a lot, because jQuery handles looping through all of them for you. Without jQuery you have to do the iteration yourself:
var divs = document.querySelectorAll('div');
for ( var i = 0; i < divs.length; i++ ) {
divs[ i ].classList.add('example')
}
Or
document.querySelectorAll('div').forEach(div => div.classList.add('example'))
document.querySelectorAll( selector ) is very similar to $( selector ), but document.querySelector( selector ) is more like $( selector ).first().

Get subclass of document.getElementsByClassName

So, I have this html code:
<div class='class1' id='example'>
<span class='class2'>Some text</span>
<span class='class3'>Some text 2</span>
</div>
I want to get every class1 and then add an event listener (click) on class2 and class3 (and I need that id to get some info from a PHP file). I tried something like this:
var yes = document.getElementsByClassName('class1');
for (var i=0 ; i<yes.length;i++)
yes[i].getElementsByClassName('class2').addEventListener('click',redirectfunction,false);
It's not working. What can I do?!
You are probably better to use querySelectorAll as it has wider support than getElementsByClassName (IE 8+) and you can get the elements in one go:
var yes = document.querySelectorAll('.class1 > .class2, .class1 > .class3');
querySelectorAll returns a static NodeList, so iterate over the returned object to access the members.
However, be prepared to provide a fallback for older browsers.
At first getsElementsByClassName should be getElementsByClassName (if not a typo) and then yes[i].getElementsByClassName('class2') returns a HTMLCollection of found elements and you are using this:
yes[i].getElementsByClassName('class2')
.addEventListener('click',redirectfunction,false);
So, you are trying to add an event listener on a collection. You may use another loop if there are multiple elements or just use something like this:
yes[i].getElementsByClassName('class2')[0]
.addEventListener('click',redirectfunction,false);
Update: (Example)
var els = document.querySelectorAll('div.class1');
for(var i =0, l=els.length; i<l; i++) {
var cls = els[i].querySelectorAll('span[class^=class]');
for(var x =0, n=cls.length; x<n; x++) {
cls[x].addEventListener('click', function(e) {
redirectfunction.call(this, e, this.parentNode.id);
}, false);
}
}
function redirectfunction(e, id) {
alert('This is id: ' + id);
}

javascript selectors

How does one select DOM elements in javascript?
Like for example:
<div class="des">
<h1>Test</h1>
<div class="desleft">
<p>Lorem Ipsum.</p>
</div>
<div class="Right">
<button>Test</button>
</div>
</div>
Now how do i select h1? This is just a part of a bigger Page, so cannot use getElementsByTagName(), since others might get selected. Also since there might be other h1's in the document later, i cannot attach the index(body's) to above.
Is there a simple way to select, say <h1> tag which is under the classname of desleft?
I cannot use jQuery or any other libraries.
You can use this to get to your H1:
var des = document.getElementsByClassName('des')
var fc = des[0].getElementsByTagName('h1')
alert(fc[0].innerHTML)
w3.org has selectors now (http://www.w3.org/TR/selectors-api/#examples). Here are 2 different ways that worked for me on Chrome. You may want to use querySelectorAll function that returns a list.
<script type="text/javascript">
//looks for <h1> tag under <div> with className "des"
showOff1 = function() {
var x = document.querySelector(".des h1");
alert(x.innerHTML);
}
//looks for <div> tag with className "desleft" and then use previousSibling to traceback <h1> tag
showOff2 = function() {
var y = document.querySelector("div.desleft");
var z = y.previousSibling.previousSibling;
alert(z.innerHTML);
}
</script>
<body onload="showOff2();">
Use querySelectorAll
You can use querySelectorAll:
// Will return a NodeList even if there is only one element found
var heading = document.querySelectorAll('.des > h1');
heading[1].style.color = 'red'; // NodeList is similar to an array
This will return a NodeList.
or
Use querySelector to return the first element found:
var first_heading = document.querySelector('.des > h1');
first_heading.style.color = 'blue';
Commonly used with an id selector #single-header-id.
Here's a demo
getElementsByTag()
Would be a function that you can start with, and then you can filter for the DOMElements that have the class.
var h1_array = document.getElementsByTag('h1');
var h1_class_array = [];
for (var i=0, len=h1_array.length; i < len; i++) {
if (h1_array[i].className.indexOf('classname') !== -1) {
h1_class_array.push(h1_array[i]);
}
}
The .indexOf function returns -1 if the needle is not found in the haystack.
Now re-reading your question, why not just give your h1's id's ?
DOM traversal is one of javascript's glaring issues (enter jQuery).
a simple getElementById() would save you a headache, and ids on all your h1's would be much cleaner in the end than trying to formulate an algorithm to select them by other means.
If you mean to select a h1 that is before the first element of class desleft, you could always do this:
document.getElementsByClassName("desleft")[0].previousSibling.previousSibling
Example: http://jsfiddle.net/Xeon06/ZMJJk/
previousSibling needs to be called twice because of the empty text node between the two. That's why using libraries to do this stuff is really the best way to go.
var h1 = document.querySelector('.desleft').previousElementSibling;
Find element with className='desleft' using selector '.desleft'
Just move back to previous element (not to previous node!)

Categories

Resources