I tried to set it up so that it checks to see if it has another variable, and if it doesn't, add it.
var item = "<li>Testing</li>";
var hasItem = $(".target-class").has(item).length;
if(hasItem == 0) {$(".target-class").append(item)}
This doesn't work and it keeps appending item forever.
.has expects a selector, not HTML:
var item = '<li class="testing">Testing</li>';
var hasItem = $(".target-class").has('li.testing').length;
Please read the documentation.
So if your HTML were:
<div class="target-class"></div>
Then the below while loop would add the div element once and then stop executing:
var item = "<li class='testing'>Testing</li>";
var targetEl = $(".target-class");
while (!targetEl.has("li.testing").length) {targetEl.append(item);}
http://jsfiddle.net/cssimsek/qdpFJ/
I actually had
var hasItem = $(".target-class").has(item).length;
messed up. It wasn't selecting what I thought it was selecting. As a tip for anyone new to jQuery, add .remove() to the end of your selector. When you are removing exactly what you want to select then you know you have it right. Just remove .remove() and you are good to go.
Along with fixing .has(item), it now works.
Related
I want to create one short userscript because I hate this annoying yellow smileys!
There are two html lines witch turns the normal smiley ( :) ) into the yellow icon
<span class="emoticon_text" aria-hidden="true"> :) </span>
<span title=":)" class="emoticon emoticon_smile"></span>
So, in the first line I have to remove the class and the aria-hidden
And in the second the whole line, it can be class="emoticon emoticon_smile", but also something like class="emoticon emoticon_cool"
I tried with:
document.getElementsByClassName("emoticon_ text").removeAttribute("aria-hidden"); document.getElementsByClassName("emoticon_ text").className = "";
but it failed, so I hope you guys can help me, because my Javescript/jQuery skills are bad..
Thank you
sorry for my grammar mistakes
document.getElementsByClassName returns a HTMLCollection, which is basically a array of elements matched. You have to iterate trough that collection and run your code for each of the elements matched.
Secondly, you'll need to find the emoticon itself and remove it, for that you need to get each emoticon's parent and tell it to remove the element. In the end, your code will look similar to this:
//Finds all emoticon texts
var emoticonTexts = document.getElementsByClassName("emoticon_text");
//Iterate over the results and remove the desired attributes
for (var i = emoticonTexts.length-1; i >= 0; i -= 1) {
var element = emoticonTexts[i];
element.removeAttribute("aria-hidden");
element.className = "";
}
//Find all emoticon images
var emoticons = document.getElementsByClassName("emoticon");
//Iterate over the results and remove them from the page
for (var i = emoticons.length-1; i >= 0; i -= 1) {
var element = emoticons[i];
element.parentNode.removeChild(element);
}
Also available as an example on JSFiddle
I would look into using jQuery. Once you have the jQuery library referenced in your project your solution should be as simple as:
$(".emoticon_text").removeAttr("aria-hidden").removeClass("emoticon_text");
I have a fairly complex situation (to me at least):
I have a click function that was used to show an overlay. Inside the click function, the element in question is determined dynamically:
$('a.overlay-show').click(function() {
var id = $(this).attr('id');
var el_id = '#project-details-overlay-' + id;
Now what I'd like to do is something like:
$(el_id).detach();
But I am seeing that this doesn't work because I am passing in an element not a selector. So how would one do this?
What I need to do is grab that element and re-attach it somewhere else. I have tried to just deal with the element's contents using .html() and so forth but because the content, at times contains javascript elements such as slideshows, this doesn't seem to work out too well...
Any suggestions?
should work this way:
$('a.overlay-show').click(function() {
var id = $(this).attr('id');
var el_id = $('#project-details-overlay-' + id);
el_id.detach();
});
i'm not familiar with detach.. if you're trying to move it somewhere else:
<div id="somewhereElse"></div>
then you would write:
el_id.appendTo('#somewhereElse');
if you want to keep it where it is AND copy it somewhere else:
el_id.clone().appendTo('#somewhereElse');
lastly, if you're not using el_id anywhere else beyond this one line of code, you don't even need the extra variable... just condense the var statement and the append statement into one:
$('#project-details-overlay-' + id).appendTo('#somewhereElse');
Thanks #erikruina - appendTo() works much better. I ended up fixing it with
$('a.overlay-show').click(function() {
var id = $(this).attr('id');
var el_id = $('#project-details-overlay-' + id);
$(el_id).appendTo('#selected-project');
});
I suspect that the issue is that with detach(); you also need to deal with all the child elements, whereas appendTo() just works.
I have a page that can have one of three possible elements. I would like to assign whatever element exists to a var and then check if the var is clicked.
I tried using the add(), but it has confused me:
var testingVar = $('#element-one').find('.object').add('#element-two').find('.object').add('#element-three').find('.object');
$(testingVar ).click(function() {
alert('works');
});
It seems to me that the add() overwrites the previous add()? if I am on a page that has #element-three, it works, if on a page with element-one or element-two, it doesn't. If I change the var to
var testingVar = $('#element-one').find('.object');
Then a page with element-one works.
Can someone help me understand how to use the add() properly in this case?
Thanks
I think what you're looking for is this:
$('#element-one .object').add('#element-two .object').add('#element-three .object');
.find() returns a new jquery object.
However, I think this would be easier in this case:
$('#element-one .object, #element-two .object, #element-three .object');
Or even easier, if you can change markup, is to give each element you're currently selecting by id a common class, and do this:
$('.common-class .object')
I have a dynamic div which can generate over 1000 different classes... its a wordpress theme.
Now i am wanting to check if a div has one of 52 classes.
.bg1, .bg2, .bg3 etc etc...
I know that you can use hasClass();
But how do I check for each one and then get the value. For instance here is the div as it stands
<div id="wordpresspost" class="bodyclass post-id-193 wordpresswrap bg1"></div>
Please bare in mind I dont really know jquery :D
I was thinking it would be something like this but logically this does not make sense to me :(
var divclass = $("#wordpresspost").hasClass('bg1, bg2, bg3, bg4, bg5, bg6');
if(divclass == true){
var divsclass = $(this);
}
I need to know the class because I want to change it, for instance i would like to .removeClass and then addClass a new class without changing the others as they are dynamic
Thanks in advance for the advice :)
Use .is():
var divclass = $("#wordpresspost").is('.bg1, .bg2, .bg3, .bg4, .bg5, .bg6');
You can use starts with selector.
Caveat with this is that if you have another class starts with bg[something] it would be impacted
if($("#wordpresspost[class^=bg]").length > 0)
{
....
}
In order to remove it probably regex might help.
$("#wordpresspost[class^=bg]").each(function(){
this.className = this.className.replace(/\bbg.*?\b/g, 'newclass');
});
var el = document.getElementById('wordpresspost');
var regxpr = /\b(bg(?:[1-9]|[1-4]\d|5[0-2]))\b/g, match;
while(match = regxpr.exec(el.className)){
// match[1] contains the current matching class
console.log(match[1]);
// Then you can do:
$(el).removeClass(match[1]).addClass(replacementForMatch);
}
JSFiddle
If you are searching for bg* in only one element, you could just use simple regex.
var hasBg = /bg[\d]+/.test(document.getElementById("mydiv").className);
I want to swap two html div tags entirely, tags and all. I tried the code below code but it does not work.
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id.next().next());
How to swap two div tags entirely.
You have some bracket mismatching in your code, it looks like you might be trying to do this:
jQuery('#AllBlock-'+Id).insertAfter($('#AllBlock-'+Id').next().next());
Which would take something like:
<div id="AllBlock-5"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>
And, if called with Id 5, turn it into this:
<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>
<div id="AllBlock-5"></div>
This is because you're taking block 5, and moving it (using insertAfter) to the place after the block that's next().next() (or next-but-one) from itself, which would be block 7.
If you want to always swap #AllBlock-Id with #AllBlock-[Id+2], so they switch places and end up like the following:
<div id="AllBlock-7"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-5"></div>
You might want to try:
var $block = jQuery('#AllBlock-'+Id);
var $pivot = $block.next();
var $blockToSwap = $pivot.next();
$blockToSwap.insertBefore($pivot);
$block.insertAfter($pivot);
You can't do this because you can't concatenate a string and a jQuery object.
Try this:
var div = $('#AllBlock-'+Id);
div.insertAfter(div.next().next());
it should be like this
you should close the bracket after Id,
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id).next().next());
You'll need to detach the existing dom object first, then re-use it later:
$('#divid').detach().insertAfter('#someotherdivid');
What I understand is you want to swap a div when clicked with the last div. What will you do if it is the last div? move it to the top?
This solution should solve the problem, furthermore, you can modify this regex to match the format of your ID. This can probably be made more concise and robust. For example, you could get the last ID a bit more sophisticatedly. This may just be modifying the selector or something more. I mean, you do not want to go rearranging the footer or something just because its the last div on the page.
$('div').click(function() {
//set regex
var re = /(^\w+-)(\d+)$/i;
//get attr broken into parts
var str = $(this).attr('id').match(re)[1],
id = $(this).attr('id').match(re)[2];
//get div count and bulid last id
var lastStr = $('div:last').attr('id').match(re)[1],
lastID = $('div:last').attr('id').match(re)[2];
//if we have any div but the last, swap it with the end
if ( id !== lastID ) {
$(this).insertAfter('#'+lastStr+lastID);
}
//otherwise, move the last one to the top of the stack
else {
$(this).insertBefore('div:first');
} });
Check out this working fiddle: http://jsfiddle.net/sQYhD/
You may also be interested in the jquery-ui library: http://jqueryui.com/demos/sortable/