Change HTML action="" using JavaScript - javascript

How can I change the string inside action="somthing" I've tried using
document.getElementsByClassName
but it doesn't seems to change anything.
My HTML
......
.........
<div class="my_button button" action='play_car'></div>
.....
......
My Javascript
document.getElementsByClassName('my_button').action = "play_boat";
.......
......
I've also tried
HTML
<div id="test" class="my_button button" action='play_car'></div>
Javascript
var a= document.getElementById('test');
console.log(a);
It just returns null

"get element-s by class name" returns a collection, not a single element.
Returns an array of all child elements which have any of the given class names. When called on the document object, the complete document is searched, including the root node.
Assuming that there is only a single element returned, then:
var elementsWithClass = document.getElementsByClassName('my_button')
elementsWithClass[0].action = "play_boat";
However, it may be more appropriate to use a loop - class names are generally designed to be used with multiple elements, and IDs (along with getElementById) for singular/unique elements.
Unfortunately, getElementsByClassName is not supported in even as "recent" a browser as IE8. To handle this, use a cross-browser library (jQuery or your preference) or a polyfill.

getElementsByClassName will return an array of all elements. Use document.getElementById if you want to address only one element. Also getElementsByClassName isn't supported by older browser. If that's an issue, you can use jQuery instead.

If you have only one element with this class name, you can get the first item:
document.getElementsByClassName('my_button')[0].action = "play_boat";
if you have many, iterate over them:
for (var i in document.getElementsByClassName('my_button')) {
document.getElementsByClassName('my_button')[i].action = "play_boat";
}
Please, check if the place of the javascript code is after the elements with the class "my_button".

Related

Why does jQuery return more than one element when selecting by type and ID? [duplicate]

I fetch data from Google's AdWords website which has multiple elements with the same id.
Could you please explain why the following 3 queries doesn't result with the same answer (2)?
Live Demo
HTML:
<div>
<span id="a">1</span>
<span id="a">2</span>
<span>3</span>
</div>
JS:
$(function() {
var w = $("div");
console.log($("#a").length); // 1 - Why?
console.log($("body #a").length); // 2
console.log($("#a", w).length); // 2
});
Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.
However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.
However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a type selector, like this:
$('span[id="a"]');
The reason for this is because a type selector is much more efficient than an attribute selector. If you qualify your attribute selector with a type selector, jQuery will first use the type selector to find the elements of that type, and then only run the attribute selector on those elements. This is simply much more efficient.
There should only be one element with a given id. If you're stuck with that situation, see the 2nd half of my answer for options.
How a browser behaves when you have multiple elements with the same id (illegal HTML) is not defined by specification. You could test all the browsers and find out how they behave, but it's unwise to use this configuration or rely on any particular behavior.
Use classes if you want multiple objects to have the same identifier.
<div>
<span class="a">1</span>
<span class="a">2</span>
<span>3</span>
</div>
$(function() {
var w = $("div");
console.log($(".a").length); // 2
console.log($("body .a").length); // 2
console.log($(".a", w).length); // 2
});
If you want to reliably look at elements with IDs that are the same because you can't fix the document, then you will have to do your own iteration as you cannot rely on any of the built in DOM functions.
You could do so like this:
function findMultiID(id) {
var results = [];
var children = $("div").get(0).children;
for (var i = 0; i < children.length; i++) {
if (children[i].id == id) {
results.push(children[i]);
}
}
return(results);
}
Or, using jQuery:
$("div *").filter(function() {return(this.id == "a");});
jQuery working example: http://jsfiddle.net/jfriend00/XY2tX/.
As to Why you get different results, that would have to do with the internal implementation of whatever piece of code was carrying out the actual selector operation. In jQuery, you could study the code to find out what any given version was doing, but since this is illegal HTML, there is no guarantee that it will stay the same over time. From what I've seen in jQuery, it first checks to see if the selector is a simple id like #a and if so, just used document.getElementById("a"). If the selector is more complex than that and querySelectorAll() exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. If querySelectorAll() does not exist, then it will use the Sizzle selector engine to manually find the selector which will have it's own implementation. So, you can have at least three different implementations all in the same browser family depending upon the exact selector and how new the browser is. Then, individual browsers will all have their own querySelectorAll() implementations. If you want to reliably deal with this situation, you will probably have to use your own iteration code as I've illustrated above.
jQuery's id selector only returns one result. The descendant and multiple selectors in the second and third statements are designed to select multiple elements. It's similar to:
Statement 1
var length = document.getElementById('a').length;
...Yields one result.
Statement 2
var length = 0;
for (i=0; i<document.body.childNodes.length; i++) {
if (document.body.childNodes.item(i).id == 'a') {
length++;
}
}
...Yields two results.
Statement 3
var length = document.getElementById('a').length + document.getElementsByTagName('div').length;
...Also yields two results.
What we do to get the elements we need when we have a stupid page that has more than one element with same ID? If we use '#duplicatedId' we get the first element only. To achieve selecting the other elements you can do something like this:
$("[id=duplicatedId]")
You will get a collection with all elements with id=duplicatedId.
From the id Selector jQuery page:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
Naughty Google. But they don't even close their <html> and <body> tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.
If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.
<div>
<span id="a" class="demo">1</span>
<span id="a" class="demo">2</span>
<span>3</span>
</div>
JQ:
$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");
Access individual item
<div id='a' data-options='{"url","www.google.com"}'>Google</div>
<div id='a' data-options='{"url","www.facebook.com"}'>Facebook</div>
<div id='a' data-options='{"url","www.twitter.com"}'>Twitter</div>
$( "div[id='a']" ).on('click', function() {
$(location).attr('href', $(this).data('options').url);
});
you can simply write $('span#a').length to get the length.
Here is the Solution for your code:
console.log($('span#a').length);
try JSfiddle:
https://jsfiddle.net/vickyfor2007/wcc0ab5g/2/

JS es6 on click add class to another element

I'm trying to show a div when another button has been clicked.
Unfortunately the site i'm using doesn't use jquery but has babel.js installed.
This is the HTML of the button the user is clicking
<button id="ba-Calculate" class="button">Calculate</button>
And this is the HTML for the button I would like to display
<button class="js-find-a-mortgage button u-margin-top-small" style="display: none;">Find a mortgage</button>
I've added a style of display none to hide the element.
This is what i've come up with so far.
var el = document.querySelector('#ba-Calculate');
el.onclick = function() {
document.getElementsByClassName('js-find-a-mortgage').style.display = 'block';
}
Any suggestions or where to read up on how I can crack this would be great.
I appreciate the feedback, thank you.
document.getElementsByClassName returns an array. So, you need to fetch the first element (I believe you have only one element with that class in the DOM) and add the style.
Try using
document.getElementsByClassName('js-find-a-mortgage')[0].style.display = 'block';
var trigger = document.querySelector('#ba-calculate')
var el = document.querySelector('.js-find-a-mortgate')
trigger.addEventListener('click', function () {
el.style.display = 'block'
})
getElementsByClassName returns an array like object
The getElementsByClassName method of Document interface returns an
array-like object of all child elements which have all of the given
class names. When called on the document object, the complete document
is searched, including the root node. You may also call
getElementsByClassName() on any element; it will return only elements
which are descendants of the specified root element with the given
class names.
Using querySelector will grab the first instance of a node matching that class name. You can then use the code you already had.
If you want to add class, I assume you need to use classList method add:
For example to add for your element class 'hidden':
document.getElementsByClassName('js-find-a-mortgage')[0].classList.add('hidden');
To see all classes use: document.getElementsByClassName('js-find-a-mortgage')[0].classList
https://www.w3schools.com/jsref/prop_element_classlist.asp

How to get elementsByClassName and then inside getElementById

Hi I'm rewriting a script from jQuery to pure JS and I don't know how else could i write this.I want to get attribute of element inside class 'form-basket' with id 'przecenajs' I know getElementsByClassName returns object of elements, and that's probably why I get the error:document.getElementsByClassName(...).getElementById is not a function
but I'm not into JS that much so i might be wrong
price = document.getElementsByClassName('form-basket').getElementById("przecenajs").getAttribute("data-procent");
That because getElementsByClassName returns a HTMLCollection object.
You probably want to use querySelector function:
document.querySelector('.form-basket #przecenajs')
console.log(document.querySelector('.form-basket #przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
or
document.getElementById('przecenajs')
console.log(document.getElementById('przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
Resources
document.querySelector()
Document.getElementsByClassName()
You do not have to select the form-basket first. Since IDs should only be used once inside a document, you can simply selct by id like so:
document.getElementById("przecenajs").getAttribute("data-procent");
I assume you are searching for more than only one tag, because if you wouldn't you could just use document.getElementById() so I think these lines do the job you want, you have to manually create the list with all the attributes to replicate the jquery behaviour:
var priceList = [];
document.querySelectorAll(".form-basket #przecenajs").forEach( (element) =>{
priceList.push(element.getAttribute("data-procent"));
});

How to return HtmlCollection from Jquery selection

I have a jquery selection like this:
elements= $($('#mytab').find('form').attr('elements')).not('button');
// access elements by name
elements['id']=1;
which is not working obviously :(
I need the jquery to return the collection as HtmlCollection e.g
$('#mytab').find('form').attr('elements')
My qeuestion is, is there any function available e.g like toArray() etc to
return the collection as HtmlCollection, instead of jquery array/ object collection ?
My main objective is to access form elements by name not by index e.g
elements['id'], elements['name']
Html Form elements
Lots of confusion around elements. elements is attribute of html form object which is collection of all the elements in the form
Here is a JSfiddle for this.
elements is a property not an attribute, you should use prop method instead:
var elements = $('#mytab').find('form').prop('elements');
or:
var elements = $('#mytab').find('form')[0].elements;
Well, if you want to filter input elements, you can use get method, there is no need to use elements property:
var elements = $('#mytab form input').get();
http://api.jquery.com/get/
Yup, there is:
$.makeArray($('div'));
This returns a array of all div elements on the page. Obviously, you can use any selector you want.
To get a array of elements, by their name, just use native JS:
document.getElementsByName('myFormElementName');

IE getelementbyid for object in the document

I need to getElementById for an object which already exists in the document.
In the example, I would like to get the element "test" which is sub of parentDiv1.
It works fine in FF but not with IE. Any tips?
Example:
<div id="parentDiv1">
<ul id="test1">test</ul>
</div>
<div id="parentDiv2">
<ul id="test2">test</ul>
</div>
<script>
var prtDiv1 = document.getElementById("parentDiv1");
var test1 = prtDiv1.getElementById("test1");
</script>
You shouldn't have more than one element with the same id in your document. Use a class. The easiest way for you to do what you want then would be to use jQuery and write $('#parentDiv1 ul.test') to select your element. Other than jQuery, you would need to implement getElementsByClassName in javascript in IE because afaik it still doesn't support it natively.
Edit: Make sure there aren't any "name" attributes that have the same value as the target id, and also that the js variable you're setting has a different name than the target id.
Calling getElementById on a node is non-standard... If you want to get the element with ID test1 (as it is its id, this one should be unique) and check that it is a child of element with ID parentDiv1 rather use this :
// get the node with ID `test1` in the document
var test1 = document.getElementById("test1");
// Check if it is a child of `parentDiv1`
var isChild = document.getElementById("parentDiv1").contains(test1);
You can look at MDN doc about contains here.

Categories