My query works great, but then I check it on IE and it is a disaster. I am wondering if it is the parent part of the code. The parents are trying to reach the first <table> containing the info. Is there an easier way to get to the table directly?
<script>
if ($('b:contains("Choose a sub category:")').length > 0) {
var newSubnav = document.createElement( 'ul' );
$(newSubnav).addClass("sub_categories_holder");
$('b:contains("Choose a sub category:")').parent().parent().parent().parent().parent().parent().parent().prepend( newSubnav );
$('a.subcategory_link').appendTo($('ul.sub_categories_holder'));
$('a.subcategory_link').wrap("<li class='sub_categories'></li>");
$('li.sub_categories').before("<li class='sub_categories_divider'></li>");
$("li.sub_categories_divider:eq(0)").remove();
$("b:contains('Choose a sub category:')").parent().parent().parent().parent().parent().remove();
$("img[src='/v/vspfiles/templates/GFAR NEW NAV/images/Bullet_SubCategory.gif']").remove();
$("td.colors_backgroundneutral").css("background-color","transparent");
$("td.colors_backgroundneutral").children(':first-child').attr("cellpadding","0");
};
</script>
Unless you provide your markup(at least a dummy one) it's all guess that you are gonna get.
Instead of .parent().parent().parent().parent().parent().parent().parent().prepend( newSubnav ); check if you can use .parents(). This will return you the parents all the way up to HTML. You can even use selectors as parents(selector) to filter. Read more on the jquery api page.
Since you are using jQuery, you can use $("ul") instead of document.createElement("ul")
Related
Lets say I have an empty div:
<div id='myDiv'></div>
Is this:
$('#myDiv').html("<div id='mySecondDiv'></div>");
The same as:
var mySecondDiv=$("<div id='mySecondDiv'></div>");
$('#myDiv').append(mySecondDiv);
Whenever you pass a string of HTML to any of jQuery's methods, this is what happens:
A temporary element is created, let's call it x. x's innerHTML is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes as a fresh DOM collection.
Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div> to jQuery(), jQuery will take a shortcut and simply do document.createElement('div').
EDIT: To see the sheer quantity of checks that jQuery performs, have a look here, here and here.
innerHTML is generally the faster approach, although don't let that govern what you do all the time. jQuery's approach isn't quite as simple as element.innerHTML = ... -- as I mentioned, there are a bunch of checks and optimisations occurring.
The correct technique depends heavily on the situation. If you want to create a large number of identical elements, then the last thing you want to do is create a massive loop, creating a new jQuery object on every iteration. E.g. the quickest way to create 100 divs with jQuery:
jQuery(Array(101).join('<div></div>'));
There are also issues of readability and maintenance to take into account.
This:
$('<div id="' + someID + '" class="foobar">' + content + '</div>');
... is a lot harder to maintain than this:
$('<div/>', {
id: someID,
className: 'foobar',
html: content
});
They are not the same. The first one replaces the HTML without creating another jQuery object first. The second creates an additional jQuery wrapper for the second div, then appends it to the first.
One jQuery Wrapper (per example):
$("#myDiv").html('<div id="mySecondDiv"></div>');
$("#myDiv").append('<div id="mySecondDiv"></div>');
Two jQuery Wrappers (per example):
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').html(mySecondDiv);
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').append(mySecondDiv);
You have a few different use cases going on. If you want to replace the content, .html is a great call since its the equivalent of innerHTML = "...". However, if you just want to append content, the extra $() wrapper set is unneeded.
Only use two wrappers if you need to manipulate the added div later on. Even in that case, you still might only need to use one:
var mySecondDiv = $("<div id='mySecondDiv'></div>").appendTo("#myDiv");
// other code here
mySecondDiv.hide();
if by .add you mean .append, then the result is the same if #myDiv is empty.
is the performance the same? dont know.
.html(x) ends up doing the same thing as .empty().append(x)
Well, .html() uses .innerHTML which is faster than DOM creation.
.html() will replace everything.
.append() will just append at the end.
You can get the second method to achieve the same effect by:
var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);
Luca mentioned that html() just inserts hte HTML which results in faster performance.
In some occassions though, you would opt for the second option, consider:
// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");
// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);
Other than the given answers, in the case that you have something like this:
<div id="test">
<input type="file" name="file0" onchange="changed()">
</div>
<script type="text/javascript">
var isAllowed = true;
function changed()
{
if (isAllowed)
{
var tmpHTML = $('#test').html();
tmpHTML += "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').html(tmpHTML);
isAllowed = false;
}
}
</script>
meaning that you want to automatically add one more file upload if any files were uploaded, the mentioned code will not work, because after the file is uploaded, the first file-upload element will be recreated and therefore the uploaded file will be wiped from it. You should use .append() instead:
function changed()
{
if (isAllowed)
{
var tmpHTML = "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').append(tmpHTML);
isAllowed = false;
}
}
This has happened to me . Jquery version : 3.3.
If you are looping through a list of objects, and want to add each object as a child of some parent dom element, then .html and .append will behave very different. .html will end up adding only the last object to the parent element, whereas .append will add all the list objects as children of the parent element.
I'm messing around with setting data into localStorage, but I'm trying to extract a value and have it populate into an empty span on a specific page load.
This is what I've been messing with, but I'm not sure if this is the correct way to go about it:
if($(".body-class-name").length > 0){
$('.title span').append($(localStorage.getItem("first_name")));
}
The only other examples I've tried to work with deal with external JSON data and that's a little too much for what I'm trying to work with.
The code does what it is suppose to. You could improve abit.
if($(".body-class-name").length > 0){
var firstname = $(localStorage.getItem("first_name");
if (firstname) {
$('#title-text').text(firstname));
}
}
Then there is some missing context in your post. But i would also look at:
Using text instead of append if you don\t want to keep append firstnames to that span.
And as others mentioned in comments be aware of your selector. I changed it to query for an ID instead.
if ( $ ( ".body-class-name" ). length > 0 ){
$ ( '.title span' ). append ( localStorage . getItem ( "first_name" )); }
The $() isn't needed around the localStorage.getItem()
You don't need using load event.
Load event is for assets files, you can use ready event.
In basically jQuery code run after document ready.
You just need to wrap with function, For example:
<h1 class="title">Hello again <span>User</span></h1>
<br/>
<label>
Enter your name here:
<input name="firstname" />
</label>
<script>
(function($){
$("input[name='firstname']").change(function(){
// Store
localStorage.setItem("first_name", $(this).val() );
});
// Load store
$('.title span').text( localStorage.getItem( "first_name" ) );
})(jQuery);
</script>
Live code here
I'm pretty new to javascript/jquery and I just built a simple slide menu.
It has 3 menus and each menu has a submenu...everything is working fine, I just want to know if there's a better way to accomplish the same task.
Here's my js code:
function menuOpen(menu){
if(menu=='menu1'){
$("#sub2").slideUp(400);
$("#sub3").slideUp(400);
$("#sub1").slideToggle(400);
}else if(menu=='menu2'){
$("#sub1").slideUp(400);
$("#sub3").slideUp(400);
$("#sub2").slideToggle(400);
}else if(menu=='menu3'){
$("#sub1").slideUp(400);
$("#sub2").slideUp(400);
$("#sub3").slideToggle(300);
}
}
without seeing your HTML:
LIVE DEMO
function menuOpen(menu){
var num = menu.match( /\d+/ ); // Regex expression to retrieve the Number
$('[id^=sub]').slideUp(); // slide UP all ID starting with sub
$('#sub'+num).slideToggle(); // get the desired ID :)
}
Use of jQuery means that we want to easily manipulate DOM elements , which means that without seeing a HTML sample of your DOM nodes and structure you're about to target it's hard to make the above even simpler.
I am messing around with a deck of cards that I made.I have it set up so that there is a method that spits out cards by suit into a list, so if I want spades I get a <ol> of all of the spades cards. I am now trying to give each <li> element an id depending on what card it is. ace will be <li id="ace"><img src="ace_spades.gif"/></li> king will be <li id="king"><img src="king_spades.gif"/></li> for example.The list is in order from top to bottom akqj1098765432 . I tried doing this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12)
{
$(document).ready(function(){
$("li").eq(counter).attr("id", card_id[counter])
});
counter++;
}
but it doesn't work. I have not really done anything with javascript before besides simple jquery stuff. What am I getting wrong here?
Try this:
$(document).ready(function(){
var card_id = ["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$.each(card_id, function(i,id){
$("li").eq(i).attr('id',id);
});
});
You should try to only have one $(document).ready() function and it's not necessary to use a while() loop.
I think you don't need to call $(document).ready() function in the while. Try this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12){
$("li").eq(counter).attr("id", card_id[counter]);
counter++;
}
You do not need the document ready function. Place your script just before </body> and after the jquery.js script. This is working for me.
Check working example at http://jsfiddle.net/H8MeG/2/
First of ID's in a webpage have to be unique. Some browsers might ignore id's of elements that have already been used. Other browsers might fail completely...
Second off. you shouldn't use .eq() like that.
You definitely shouldn't add 12 new $(document).ready() statements.
Here's a more reliable version and the example on jsfiddle
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$("#spades li").each(function(index){
$(this).attr("class", card_id[index]);
$(this).text(card_id[index]);
});
I also added $(this).text(card_id[index]); so you see it actually works. Try to uses classes for multiple elements that share the same characteristic.
why are you messing with ids at all?
you know that the first item is the ace, the second the king, and so on.
ol.getElementsByTagName('li')[12]='deuce'
I'm writing a Greasemonkey script, which redirects the user if there's only one search result to that one page. I'm trying to get the link from a table, which has many parent tables. That part of the page that I'm trying to get the link from looks like this:
<tr class="odd">
<td class="name first">
Text
</td>
Tried document.getElementById('name first'), but still no success. I need help without any external libraries. The page has a design of darkening the background of even cells, so if there's no class called 'even' then it assumes that there's only one result, and that part works correctly.
You are probably safe to use getElementsByClassName, as this is a Greasemonkey script and those browsers probably support it:
var td = document.getElementsByClassName('name first')[0];
var a = td.getElementsByTagName('a')[0];
Based on the target page and your apparent purpose (follow the first result link, if there are is only one search result), the code you want is this:
var EvenRow = document.querySelector ("table.listing tr.even");
if (EvenRow == null)
{
var ResultLink = document.querySelector ("table.listing tr.odd td.name.first a");
if (ResultLink != null)
window.location.href = ResultLink.href;
}
Notes:
There are multiple nodes with both the "name" and "first" classes. This is the reason for the more specific selector. It's also the reason why Nathan's answer failed (he ignored the tr.odd, for some reason).
A checkExistOfEven() function is not needed.
In this case, you probably want window.location.href = rather than window.location.replace(). The former preserves the search-results page in the history, in case there is some hiccup.
using document.querySelector is probably easier:
var a = document.querySelector("td.first.name a");