How to choose the elements from the jQuery object - javascript

I'm sorry for stupid title.
Problem: I need to select only .special element from $elements variable.
<div class="element"></div>
<div class="element special"></div>
<div class="element"></div>
Jquery:
var $elements = $('.element'),
$special = $element.find('.special'); // Not working.
UPD:
Please, don't write something like "$('.element.special')". It's wrong for my case.

You need to use .filter()
var $elements = $('.element'),
$special = $element.filter('.special');
Since the element you are targeting is a member of the $element set, you need to use .filter(), .find() is used to find descendant members of the elements in the calling set

< div class="element">bbb< /div>
< div class="element special">aaa< /div>
< div class="element">aaa< /div>
var $special = $('.element.special');
$special.html("test");

you can use
var $special = $('.element.special');

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>

Why wont my onclick not remove any of my classes?

I have a huge problem here.
I can't get my onclick to work as I want .. So I hope someone here can help me.
#NiceToKnow
<div id="cards" class="nice"></div>
<div id="cards" class="nice"></div>
<div id="cards" class="nice"></div>
<div id="cards" class="video"></div>
I want it to display: none; every of my class="nice", so you only can see class="video", but nothing happens at all.
You are selecting the elements of the class not the class itself. So you will have to loop through the elements as javascript can only edit what is in the DOM not the CSS classes that effect your elements. So getElementsByClassName returns an array of nodes in which we must loop through and hide each one. Click runsnippet below to see this work
function changeNice(){
//ASSIGN ELEMENTS TO ARRAY
elementsofClass=document.getElementsByClassName('nice');
for(i=0; i<elementsofClass.length; i++){
//HIDE SELECTED ELEMENT
elementsofClass[i].style.display='none';
}}
#NiceToKnow
<div id="cards1" class="nice">TEST 1</div>
<div id="cards2" class="nice">TEST 2</div>
<div id="cards3" class="nice">TEST 3</div>
<div id="cards4" class="video">I don't HIDE</div>
Also don't use duplicate ID. This will cause errors later when trying to select your elements.
The getElementsByClassName will return an array, so we need to iterate through the array and hide one by one.
So it is better to declare a function and define the logic inside that. Please see the example below.
window.hideAllniceClass = function () {
var elems = document.getElementsByClassName('nice');
for (var i = 0; i != elems.length; ++i) {
elems[i].style.display = "none"; // hidden has to be a string
}
}
#NiceToKnow
<div id="cards1" class="nice">Test Content</div>
<div id="cards2" class="nice">Test Content</div>
<div id="cards3" class="nice">Test Content</div>
<div id="cards4" class="video">Test Video Content</div>
DEMO
Change your code to something like that:
var elems = document.getElementsByClassName('nice');
for(var i = 0; i < elems.length; i++) {
elems[i].style.display = 'none'
}
You have to iterate on the results returned by getElementsByClassName.
jsfiddle
You can create a loop that will loop through all the nice elements and then display none like this: https://jsfiddle.net/7vf9pz8u/
<script>
function hide(){
for(ct=0; ct < 3; ct++){
document.getElementsByClassName('nice')[ct].style.display='none'
}
}
</script>
getElementsByClassName returns array of all the match elements so you will have to provide index or loop through all of them to change their property.
Change your code to this
document.getElementsByClassName('nice')[0].style.display='none'
//For every element
var e = document.getElementsByClassName('nice');
for (i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
As your divs do not have unique names they are in an array cards[].
So to access a particular div you need to reference the the array to that particular div. The quoted solution should work.

JavaScript - how to delete elements that do not have a specific class?

I want to delete all elements that do not have the class 'stay'
For example:
<div class="stay">Stay</div>
<div class="stay">Stay</div>
<div class="go">Go</div>
<div class="element">Stay</div>
<div class="Sel">classy</div>
I would like some javascript that would delete the elements that do not have the class stay and Sel, without having to list the classes go and element
I have used:
var els = document.querySelectorAll('#parent :not(.stay)');
for (var i = 0; i < els.length; i++) {
els[i].parentNode.removeChild(els[i])
}
from the first answer, but am unsure of how to keep the class 'Sel'.
Also, I DO NOT want any Jquery.
When you are doing such an operation should need to target a particular parent element, else it could also remove elements like html/body etc.
So assuming you have a parent node, you can use querySelectorAll in conjunction with :not() selector
<div id="parent">
<div class="stay">Stay</div>
<div class="stay">Stay</div>
<div class="go">Go</div>
<div class="element">element</div>
</div>
then
var els = document.querySelectorAll('#parent :not(.stay)');
for (var i = 0; i < els.length; i++) {
els[i].parentNode.removeChild(els[i])
}
Demo: Fiddle

About getElementById find multiple id name?

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.

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