I want to add class on siblings of target Element in javascript. I have done this before using jquery which is pretty easy. But In my current organization they do not use jquery and I need to done with javascript and that is very difficult for me.
I have write some code that will attached a click function to an matched element but afterward I am not getting any login to how to make it happend. fiddle
var elements= document.getElementsByTagName('*'),i;
i=0;
while(elements[i]){
if(elements[i].className=='c'){
elements[i].addEventListener('click',function(){
this.jsSiblings().jsAddClass('newClass')
})
}
i++
}
Array.prototype.jsSiblings= function(){
//code
}
Array.prototype.jsAddClass=function(){
//code
}
You can use the base function in JS to add a class, element.classList.add("anotherclass"); (from MDN) and here you will find out about siblings without jQuery : How to find all Siblings of currently selected object
Related
So I try to select a div within another div. My html goes like this:
<div id="Stage_game_page1"><div id="cube0">[...]</div><div id="cube1">[...]</div></div>
I want to select my #cube0 within my Stage_game_page specifically, with jQuery or JS.
The goal of the selection is to use it in an loop.
I tried :
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#Stage_game_page")$("#cube"+i)[...]
}
I don't understand what I'm doing wrong.
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#cube"+i);
}
This is sufficient to select the "#cube0"/"#cube1"/"#cube2" etc. especially since ids are always unique. To answer the question $("#cube0", "#Stage_game_page")... that is how you select a div in another div
The id attribute should only be used once! I see above that you're using id="cube0" twice. If you want your divs to be recognized in multiple instances, use a class instead (the . instead of the #). Using the same id twice will probably break your script.
I believe for your html, you could use id "cube0", "cube1", etc., as long as you're ok with entering them manually. That should work for the loop you'd like to use.
Loops through each div that starts with the id cube inside Stage_game_page1
$("#Stage_game_page1 > div[id^='cube']").each(function () {
alert($(this).html());
});
JSFiddle
Child Selctor
Starts with Selector
use each() for loop.
$('#Stage_game_page1').children().each(function(index) {
// your code here with index starts from 0
});
or this using jquery attribute starts with selector
$('#Stage_game_page1').find('[id^="cube"]').each(function(index) {
// your code here
});
You need to use .find() or .children() or the like.
The correct jQuery usage would be
$("#Stage_game_page").find('#cube'+i)
to find a div with that id inside the container #stage_game_page
You have duplicate cube0 in your html code..
and i think the look should contain something like that:
$("#cube"+i)[...]
One another solution is:
$("#Stage_game_page1 div[id='cube0']")
Currently, I have this code:
$(document).ready(function(){
// #filtertab-00 replace this with your element id
$('#filtertab-00 .box-content .es-nav .elastislide-next, #filtertab-00 .box-content .es-nav .elastislide-prev').click(function() {
// trigger lazy load
$("#filtertab-00 img.lazy").each(function(i) {
$(this).delay(150*i).fadeIn(1000, function() {
var src = $(this).attr("data-original");
$(this).attr('src',src);
});
});
});
});
and i want to use this function to target object names (id) as below:
filtertab-00
filtertab-10
filtertab-20
filtertab-30
filtertab-40
filtertab-50
filtertab-60
....
filtertab-90
Does anyone know how to use the loop function to get it work?
i just want this:
when i click pre or next button after i select a tab(name varies from filtertab-00 to filtertab-90),it will activate lazyloading for images at current selected tab.
any idea is welcome!
Perhaps you could use jQuery's attribute-starts-with selector. You can then just select all IDs that begin with filtertab- using jQuery like this:
$('div[id^="filtertab-"]').each( //magic goes here );
Note: This method is slow because it has to search the DOM for elements with IDs that meet the criteria, but it does the job. I've never noticed an appreciable latency.
This is solved through selector magic as filoxo described but since you want the images, here's another version involving find() to get your actual images.
$('div[id^="filtertab-"]').find("img.lazy").each(function(i) {
$(this).delay(150*i).fadeIn(1000, function() {
var src = $(this).attr("data-original");
$(this).attr('src',src);
});
});
In addition to that, check out the impressive list of jQuery selectors. They cover a lot of ground :)
I have this line of code:
$('#sitesAccordion .groupOfSites').click(function() {
var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
console.log(lastOpenSite);
});
I get "false" instead of getting one of the other elements (assuming that there is one - and there must be). I guess the problem is with:
.hasClass(':not(.closedTab)');
What is the problem?
My purpose is to create my own accordion (without using jQuery UI)
and I am trying to write it like this:
$('#sitesAccordion .groupOfSites').click(function() {
//Get the last opened tab
var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
//Close last opened tab and add class
lastOpenSite.hide().toggleClass('closedTab');
//Open the current Tab
$(this).children('.accordionContent').toggle('fast');
// remove class from open tab
$(this).toggleClass('closedTab');
});
Is this the best way?
thanks,
Alon
Use the not function instead:
var lastOpenSite = $(this).siblings().not('.closedTab');
hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.
It's much easier to do like this:
if(!$('#foo').hasClass('bar')) {
...
}
The ! in front of the criteria means false, works in most programming languages.
jQuery's hasClass() method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.
For ex: x.hasClass('error');
You can also use jQuery - is(selector) Method:
var lastOpenSite = $(this).siblings().is(':not(.closedTab)');
I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.
$(this).siblings(':not(.closedTab)');
I have a list that every bock is constructed like below. Some of the blocks have a <span class="protected-icon"></span>. I would like to make a really simple greasemonkey plugin that removes that block. So, my question is using Javascript how can I remove/hide the entire block ( <div data-item-type="user" class="js-stream-item stream-item"></div>that contains it?
<div data-item-type="user" class="js-stream-item stream-item">
<div class="user-content-rest">
<span class="user-name">
<span class="protected-icon"></span>
</span>
</div>
</div>
How to do it without jQuery:
var p = document.getElementsByClassName('protected-icon');
for (var i=p.length; --i>=0;) {
p[i].parentNode.removeChild(p[i]);
}
http://jsfiddle.net/sRs4s/1/
UPDATE If you want to remove the entire stream-item block, you have to loop up to it:
var p = document.getElementsByClassName('protected-icon');
var cstr = "stream-item";
for (var i=p.length; --i>=0;) {
var n = p[i];
while(n.className.split(" ").indexOf(cstr)==-1) { // won't work in older browsers
n = n.parentNode;
}
n.parentNode.removeChild(n);
}
http://jsfiddle.net/sRs4s/3/
See Best way to find if an item is in a JavaScript array? if you need to support older browsers.
To hide you can use the .hide() method.
To remove you can use the .remove() method.
Now to target the block you want
// change hide to remove for complete removal from the DOM.
$('.stream-item:has(.protected-icon)').hide();
will hide all the divs with class stream-item that contain an element with class protected-icon
Demo at http://jsfiddle.net/gaby/eeuQd/
Update
Here is a reference on using jQuery with greasemonkey How can I use jQuery in Greasemonkey?
I read that you are trying to use this with twitter page. Twitter is using Ajax requests to load parts of the page (and load new tweets..) so you might need to use an interval to your script that that it gets re-applied periodically..
That is because your code might run before the twitter has actually loaded the tweets in the page..
something like
setInterval(function(){
$('.stream-item:has(.protected-icon)').hide();
}, 2000 ); // 2000 means every two seconds (in milliseconds)
With JQuery you could do the this to hide the block:
$(document).ready(function() {
$('span.protected-icon').hide();
});
Or to remove it:
$(document).ready(function() {
$('span.protected-icon').remove();
});
Use jQuery's closest() and .remove():
$('protected-icon').closest('div[data-item-type="user"]').remove();
You could also hide the element for later use:
$('protected-icon').closest('div[data-item-type="user"]').hide();
I'm not very familiar with Greasemonkey but I noticed you tagged this as jQuery, so I'm assuming you would get use out of a jQuery script.
I would do this in case you want to bring it back at some point:
$('.protected-icon').parents('.js-stream-item.stream-item[data-item-type=user]').css({'display':'none'});
It is simple using jQuery. Add the following in the top area of your greasemonkey script:
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
Then use the following jQuery:
$('span.protected-icon').parents('.js-stream-item').hide();
Update: Sorry, I had a typo. parent should have been parents.
See the question asked here, which is a different question but contains the answer :-)
Remove element by id
edit: assuming you mean pure javascript, if you are using jQuery see all the other answers!
This should work:
$('span.protected-icon').parents('.user-content-rest').remove();
That will find all the spans with the protected-icon class, then traverse the DOM tree until an element with the user-content-rest is encountered and remove that object.
I have the following line of code
document.getElementById("divName").style.display = "none";
How do I hide a bunch of layers at once with totally different names without writing the line of code that often?
Thanks
Felix's thoughts are good. There's a third way: Since they all share a common ancestor (body), you can hide them by adding a class to body and having rules in the CSS that match the actual elements in question, like so:
body.foo table {
display: none;
}
That would hide every table on a page if you added the class "foo" to body, like this:
document.body.className += " foo";
...and then show the tables again if you removed it:
document.body.className =
document.body.className.replace(/\bfoo\b/, '');
Live example
Naturally, that selector can be a lot more discerning:
body.foo div.magic > table {
display: none;
}
That would only hide table elements that were immediate children of a div with the class "magic" (and only when body had the class "foo").
Off-topic: If the approach above doesn't suit (and it doesn't suit a lot of situations), JavaScript libraries like jQuery, Prototype, YUI, Closure, or any of several others can make manipulating sets of elements (in the ways that Felix mentioned) dramatically easier than going it alone.
Option 1 -- Create a function
function hideDiv(divname) {
document.getElementById(divname).style.display = "none";
}
Option 2 -- Hide a parent element
If all of the elements can be put inside of a parent element or already are, you can simply hide that parent element.
Option 3 -- Use a framework
A javascript framework like jQuery or MooTools will have a convenient coding convention such as .hide()
jQuery: -- see http://api.jquery.com/hide/
mooTools -- see http://mootools.net/docs/more/Element/Element.Shortcuts
Also, frameworks have tools for more complex situations and will allow you to select children of elements or a particular class and iterate through them. They can come in very handy when working with a page that has dynamically created content.
`
// jQuery Example 1: class-hiding
$(".elementsToHide").hide()
// jQuery Example 2: hiding divs within element "#whatever"
$("div", "#whatever").each(function() {
$(this).hide();
});
If they all have the same parent/ancestor, hide the parent (if possible).
Get the references to that elements, put them into an array and loop over them.
var divsToHide = ["thisDiv", "thatDiv", "divName"];
for (var i=0; i<divsToHide.length; ++i)
{
var div = document.getElementById(divsToHide[i]);
if (div) div.style.display = "none";
}
Or, you could use a framework like jQuery, and give the hidden divs some attribute in common, like a class of "hidden". Then,
$(".hidden").hide();
Course, in that case, you could also just set display: none on the class via CSS.
If they are from the same class you could select all elements of that class and loop through them. If they are all of the same parent you can select all the children, loop through them, filter if necessary and hide them this way.
var names = ['divName1', 'divName2','divName3'];
for ( i in names ) document.getElementById(names[i]).style.display = "none";