Change all links of a particular class on page load - javascript

On this site, all the links inside inventory class need to be changed to this link. I can't find the file to edit it and change the link so I am using JavaScript to do it. I have written the following code but it doesn't work.
<script type="text/javascript">
document.getElementByClass("inventory").href="http://www.inspuratesystems.com/mandviwalla-motors/contact/";
</script>

Correct syntax:
document.getElementsByClassName("inventory")
if there's only one such link on webpage try accessing the first element as above method returns array of DOM objects
document.getElementsByClassName("inventory")[0].href

It should be getElementsByClassName not getElementByClass(typo)
It returns an array-like object of all child elements which have all of the given class names.
Try this:
var elems = document.getElementsByClassName("inventory");
for (var i = 0; i < elems.length; i++) {
elems[i].href = "http://www.inspuratesystems.com/mandviwalla-motors/contact/";
}

is it possible to use jquery ?
try following
$(document).ready(function(){
$('.inventory').each(function(){
$(this).attr('href' , 'http://www.inspuratesystems.com/mandviwalla-motors/contact/');
})
})

You can do this with Jquery
$(document).ready(function () {
$("#link").attr("href", "#someOtherPlace");
});
<a id="link" href="#somePlace">LINK</a>
<!--NOTICE THE HREF VALUE-->

Related

documents get elements by classname apply to all element

I am new to JS. I want to change css for all elements selected by className. I did some search and I found the solution below. But, it will only affect the first element. I am wondering if there is a easy to to change the css for all selected elements.
document.getElementsByClassName('ads')[0].style.display = 'none';
document.getElementsByClassName('class')[x]
may be x can be 0,1,2,... depends on elements with that class if there two div with ads
class you will count from 0 as the first div with that class because it returns in array
or you can use tag name while you are selecting
document.getElementsByTagName('div')[x]
this also returns in array because in html suppose to be many similar tags means that you have to index to them
document.getElementById('id')
this is selecting by using the tag's id and an id there a tag with an id should be the unique thats why this doesn't return in array means that you don't need to index on it
document.querySelectorAll('p .class')[x]
with selector you do it like you do in css but it returns in array to and also you can apply the pseudo classes and elements
document.querySelector('p .class')
this used like the above one but it didn't return in array so you don't have to index on it
NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach;
document.querySelectorAll('.ads').forEach(ele => {ele.style.display = 'none'});
This should do it. The querySelectorAll-method returns you a Nodelist from a given css-selector. The first line checks if there is already a forEach method and if not it will inherit it from the Array Object.
You can also read about the from method of the Array object this could be a more cleaner version.
You need to use loop, please check snippet
NOTE: I added '.hide' class and set background color just to display result. you just add display:none in CSS
window.onload = function() {
var ads = document.getElementsByClassName("ads"),
len = ads !== null ? ads.length : 0,
i = 0;
for(i; i < len; i++) {
ads[i].className += " hide";
}
}
.hide {
background: skyblue;
}
<div class="ads">1</div>
<div class="ads">2</div>
Simple with jQuery method :
$('.ads:first').hide();
$('.ads:first').css("display":"none");
To using jQuery, you have to add jQuery plugin inside <body> tag before jQuery function call :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

select html with native javascript

I want to toggle a class to the html tag element. I've made it work with the body element but I cannot find the solution to also toggle a class to the html tag.
document.querySelector('[data-menu-mobile]').addEventListener('click', function(){
document.body.classList.toggle('nav-main-mobile-open');
document.html.classList.toggle('html-color-fill');
});
I know this seems to be wrong:
document.html.classList.toggle('html-color-fill');
What is the correct way to do this?
There's no document.html object, to get to the root element you should use document.documentElement.
document.documentElement.classList.toggle('html-color-fill')
This should work:
var elements = document.getElementsByClassName("myclass");
//iterate through all found elements
Array.prototype.forEach.call(elements, function(element) {
element.className = "html-color-fill";
//or remove class with:
//element.className = "";
});

Using jQuery, how to specify with the `.attr` method, the second of two html classes?

When using jQuery and are using the .attr method as follows:
$(document).ready(function(){
$('.class1').click(function(){
id = $(this).attr('.class2');
});
});
Say I have the following HTML for the above function:
<div class="class1 $class2"></div>
The second class is attributed at runtime, so I have 10 divs, each with class1, but several with class2. Then I wish to use the jQuery function at the top, so that whenever I click on any of the divs, it applies the specific class2 of that div, to the variable ID.
I hope this makes more sense.
Since your class2 comes from your PHP code, you seem to hit the usecase of data-attributes.
With data-attributes you can easily have some extra data (often used for javascript purposes) on your HTML elements without having to use special classes or ids for that.
It works like that:
<span data-hero="batman">I'm a Bat!</span>
Where in your Javascript (using jQuery) you get the value of it by simply doing:
$('span').data('hero');
Refer to the MDN and the jQuery documentation for further information.
Is this what you're trying to do?
$(document).ready(function(){
$('.class1').click(function(){
var id = $(this).attr('class').replace('class1','').trim();
});
});
If you have a multi class tag this mean the HTML code would be like this:
<sometag class="class1 class2">...</sometag>
I think the simplest approach is to do some string operations on the class attribute of the tag:
var class2 = $(selector).attr("class").split(" ")[1];
OR you can write a simple jQuery plugin to do the work for you:
(function($){
$.fn.secondClass = function(){
var c = this.attr("class").split(" ");
if(c.length >= 2)
return c[1];
};
}(jQuery))
Usage: var class2 = $(selector).secondClass();
Hope this helps.

How can I assign click function to many buttons using JQuery?

I have 29 buttons: todayResultsbutton0 .. todayResultsbutton28,
and 29 divs: todayResultsUrls0 .. todayResultsUrls28.
I also have a function toggleVisibility(divName) that hide/show the given div.
I am trying to use the following code:
for (var i=0; i < 29; ++i) {
var b = "#todayResultsbutton"+i;
var d = "todayResultsUrls"+i;
$(b).click(function(){toggleVisibility(d);});
}
I thought that this will cause each button click to show/hide the matching div but the actual result is that clicking on any button (0 .. 28) show/hide the last div - todayResultsUrls28.
Can someone tell me where am I wrong?
Thanks.
Use a class.
$(".myClass").click(function() {
var d = $(this).attr("id").replace("button", "Urls");
toggleVisibility(d);
});
Instead of trying to use a loop, you'd be better off using the selector to "find" your divs..
say you have something like:
<table>
<tr><td>
<input type="button" id="myButton" value="test" text="test" />
</td><td><div id="myDiv"></div></td></tr></table>
You can find myDiv by :
$('#myButton').parent().find('#myDiv').hide();
You could use the "startsWith" attribute selector with the id, then build the url from the id of the clicked item.
$('[id^=todayResultsbutton]').click( function() {
var url = this.id.replace(/button/,'Urls');
toggleVisibility(url);
});
Use
var d = "#todayResultsUrls"+i;
Instead of
var d = "todayResultsUrls"+i;
You can use this:
$('button[id^="todayResultsbutton"]').click(function() {
var index = this.id.substring(18,this.id.length);
toggleVisibility("todayResultsUrls"+index);
});
This will find all <button> tags with id's starting with todayResultsbutton. It will then get the ID for the clicked tag, remove the todayResultsbutton part of it to get the id and then call the toggleVisibilty() function.
Example here.
Edit
Notes:
Using button before the starts with selector ([id^="todayResultsbutton"]) speeds up the jQuery selector because it can use the native getElementsByTagName function to get all button tags and then only check those for the specific ID.
this.id is used instead of jQuery's $(this).attr('id') because it's faster (doesn't require wrapping this or calling the extra function attr()) and shouldn't cause any cross-browser issues.
Toggle visibility by finding the relevent div usint the event target rather than classes etc.
Assuming:
<div id='todayResultsUrls1'>
<button id='todayResultsbutton'></button>
</div>
Using the event target you can get the button element and find the div you want to hide.
var parentDiv = $(e.target).parent();
toggleVisibility(parentDiv);

using document.getElementsByTagName doesn't find elements added dynamically (IE6)

I am trying to write a method that grabs all the elements of a certain classname for browsers that don't have the 'getElementsByClassName' method. This works perfectly for elements that are generated server-side, however the page has the ability to add elements dynamically for some reason 'window.document.all' does not get these dynamic elements. Any ideas? Method below.
function getClassName(class) {
var i, neededStuff = [], elements = document.getElementsByTagName('*');
for (i = 0; i < elements.length; i++) {
if (elements[i].className == class) {
neededStuff[neededStuff.length] = elements[i];
}
}
return neededStuff;
}
class is a reserved keyword in IE. Don't use it literally. Change class to something like theClass.
Also, try document.getElementsByTagName('*') instead of document.all if changing class doesn't do it.
EDIT:
http://work.arounds.org/sandbox/72
Works perfectly for me in IE6 ^
Let me try dynamically adding...
EDIT #2: works fine..
http://work.arounds.org/sandbox/72
Use jQuery :)
http://jquery.com/
$('.ClassName')
will return your elements :)
then you can change it's value, add classes very easily!
Some great tutorials here
http://docs.jquery.com/Tutorials

Categories