I am really new to JavaScript, and Im basically trying to build a simple Script to get information from a site like Walmart.com. Im using firebug to test my little snippets. Im having a problem getting the price.
This is the my code:
var price = document.getElementById('clearfix camelPrice');
console.log(price);
I also tried ".camelPrice" with out the period and I keep getting null.
Thanks a lot in advance!
In this case, you're using the wrong method. getElementById does exactly what it says, it gets an element by its id. Looking on Walmart.com, 'camelPrice' is a CSS class.
We can still get elements by a class. What you want is document.getElementsByClassName(). Further, you can pass multiple arguments to getElementsByClassName like so:
document.getElementsByClassName('clearfix', 'camelPrice');
This grabs all elements that have both the clearfix and camelPrice classes set.
In addition to what the others have said about your selection looking like ids, here is how you can select by class name:
document.getElementsByClassName('classname');
Newer browsers allow you to make jQuery-like selections from native JavaScript:
document.querySelectorAll('#id .classname');
http://caniuse.com/queryselector
It looks like you're trying to provide a class selector to getElementById instead of an ID selector. This is what an ID looks like:
<div id="some-id">...</div>
This is what a class looks like:
<div class="some-class">...</div>
The difference is that only one element should ever have a specific ID on a page, where many elements might have the same class.
I am not sure how you are running your JavaScript in Walmart's site, which is not impossible, but maybe you should specify it, for instance if the Walmart site is in an iframe you will not be able to use getElementById() from your site.
On the other hand if you are running some sort of local Live Editor/Console, then maybe it is possible.
For the script you show above, you have an error on the ID since an id can only be one word, and you are missing to select what type of attribute you want from the element:
For example, <input>:
var price = document.getElementById('id').value
or for other tags like <div>:
var price = document.getElementById('id').innerHTML
Related
Kind of a newbie to this but I have followed a totorial on a memory game as an attempt to understand the syntax of JS but am stuck on making the round result print in a instead of showing up as a alert
here is a codepen here.
how can I print round in a <span> <!-- result here--> </span> rather than like this alert("result")
How can I make it set to a span instead of being an alert?
Browsers parse HTML into a tree of objects called Document Object Model (DOM). Using JavaScript you can query the DOM to get individual nodes, and then change them.
To get your span, you would typically use document.getElementById or document.querySelector (there are other functions that can fetch collections of related nodes, like document.getElementsByClassName or document.querySelectorAll). The former identify nodes by the property named in the method name (ID, or class name, respectively); the latter ones use CSS selectors. (All of the getElement... functions can be replicated using the newer querySelector and querySelectorAll interface, though you have to know how to use CSS selectors. I almost never use getElement... functions any more.) There are also functions that use XPath, though this is a bit more advanced subject.
Once you have the node, you can change its content using e.g. .textContent or .innerHTML properties, the former being for plain text, the latter for HTML.
For example, if this is the only span on the page, this suffices:
document.querySelector('span').textContent = "Result";
<span></span>
If on the other hand you have more of them, you would need some way to target the correct one. I will also demonstrate how you can style it using HTML:
const node = document.querySelector('#result_goes_here');
node.innerHTML = "<strong>Result</strong> in bold!";
<span id="result_goes_here"></span>
If you are trying to add the result inside the HTML SPAN and not in the alert box. You can do it something like this:
document.getElementById("span_ID").innerHTML = the_variable_result_here;
Hope that helps!
I came across some year old code written by a good developer (yes, I knew him personally) to access all elements having the same id.
$("#choice,#choice")
It returns all elements having the id. But if we use the below
$("#choice")
It returns only the first match, as expected.
After searching for some time, I'm unable to figure out any official links pointing to his technique, as to how it selected all elements with duplicate id.
Can anyone please explain how is this working ?
UPDATE
Please see the question is not about what alternative to use. I'm aware of classSelectors and attributeSelectors and know having duplicate IDs is not recommended, but sometimes you just have to live with years old code the way it is (if you know what I mean).
http://jsbin.com/zodeyexigo/1/edit?html,js,output
If you look at the code of sizzle.js that jQuery uses for selecting elements based on selector you will understand why this happens. It uses following regex to match simple ID, TAG or class selector:
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
but as the selector in question is $("#ID,#ID") it does not match with the selector and uses querySelectorAll (line no 270 in ref link), which replaces selector to "[id='" + nid + "'] " (line no 297 in ref link) which selects all the elements with matching ID.
However, I agree with the other people in this thread, that it is not good idea to have same ID for multiple elements.
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 tag selector, like this:
$('span[id="a"]');
Having duplicated id on the page making your html not valid . ID is unique identifier for one element on the page (spec). Using classes, that are classify similar elements that's your case and $('.choice') will return set of elements
So in JS Fiddle i have shown an example of what jQuery is doing.
https://jsfiddle.net/akp3a7La/
When you have a
$('#choice,#choice');
It is actually getting all the instances of the objects #choice twice, and then filtering out any duplicates.
in my example i show you how it does that also when you have something like this
$("#choice,li");
Where items are actually your #choice items.
In the Jquery Documentation
https://api.jquery.com/multiple-selector/
it talks about multiple Selectors, which is what i think is happening here, your developer friend is selecting the same ID twice, and it would be returning it twice. as you can only have one input with the same ID once on a page (good html syntax)
I am in a position where I need to use the .slideToggle() function in jQuery, on a regular JavaScript determined element.
I can use this code:
var feedback = document.getElementsByClassName('feedback');
and then a bit later on in a function:
feedback[index].style.display = 'block';
However, what I want to do is use the slideToggle('fast') function on feedback[index], so instead of so brutally changing its display to block, I get a nice jQuery-esque transition.
Obviously this code won't work:
feedback[index].slideToggle('fast');
However this will:
$('.feedback').slideToggle('fast');
but I can't choose which feedback by index to run the slideToggle() function on, it just does them all, which makes sense.
If I could get some code that effectively does this:
$('.feedback')[index].slideToggle('fast');
That would be perfect. I like the fact that I can stick a class on something and iterate through the list of items that appear in .getElementsByClassName('classname'), so I don't have to stick an ID on everything of the same class, and it would be nice if I could choose which $('.feedback') element I am using in the list of all elements returned by this but I cannot figure out how that would work. If I can somehow choose by index which items in a list by class, to run jQuery commands on it would make this a lot simpler as I do not want to stick an ID on each and every item that has the class of feedback.
Thanks a lot.
Try this : You can use eq() to select element with specific index.
$('.feedback:eq('+index+')').slideToggle('fast');
You can use JQuery like this:
$(feedback[index]).slideToggle('fast');
Here you can see demo
I have common jQuery function and two div tags. Both div tags have different names but both containing elements of identical ids now i want to use this common Jquery function for them both?
I have implemented common function but it's not working for both.
Here's link to my jsfiddle -jsfiddle.net/xS7zF/1/
In my jsfiddle there are two div tags namely example1 and example2 and both tags have elements of identical ids. Function is working fine for first div but not for second.
please help me to sort out this.
Yeah, under the hood, jQuery selection on an ID will use the Document.GetElementById() function implemented by the browser, which is really fast, but (i guess depending on the browser) will stop after it finds the first element, since ID's should be unique and no further searching is needed after the first one is found.
For instance, rename the divs with id="eb" to class="eb" and you can still target specific elements using $("#example1 .eb") and $("#example2 .eb")
UPDATE:
Using your new Fiddle I created this: http://jsfiddle.net/xS7zF/5/
I cleaned up a lot of code and hopefully you can see what I have done. I changed all elements that appear twice from id to class. Now, when you attach an event to an element using $(".classname").click(), it attaches to all the elements. In the handler function where you set HTML and do your show()/hide(), you don't target a specific element using it's ID, but you find it relative to the element that does the event. You can do this using parent(), parentsUntil(), next(), find(), etc. Check jQuery docs for all possibilities. So for instance, the change-handler attaches to all inputs with name=Assets. But instead of doing $("#b1").show(), I go to the parent of the specific input that fires using $(this).parent(). Then I find the element with a class=".b1", which it will only find the one that is next to this specific input and I set the HTML to just that element.
Since there is another input, the same actions happen when THAT input changes, but instead it finds IT's parent, and finds the element with class=".b1" that is next to IT. So both divs with input are contained since they act on elements relative to itself and not across the document.
For extra fun and to show you how flexible this way of programming is, here is a fiddle with the Javascript-code unchanged, but with the exact same question-div copied 8 times. No matter how many times you repeat this, the same code will act on as many divs as you create since everything works relative. http://jsfiddle.net/xS7zF/7/
Hopefully this helps, the rest is up to you!
ID's must be unique, you should not repeat them. You could replace id with class and in the jQuery function do (".ub").each() or manually referencing the object using eq(x). e.g. (".ub").eq(1).
You shouldn't assign same id's to different elements.
You CAN but you SHOULDN'T. Instead of giving the same id, use class
IDs must be unique, try fix this, change to classes.
You can try something like this:
$("div div:first-child")
instead of
$("#eb")
But depends of the rest of your page code. So, change to classes first and use
$(".eb")
when jQuery / javascript find the first ID it would ignore the rest, please read more about it
http://www.w3schools.com/tags/att_global_id.asp
I just wanted a fast/easy/simple way to check for existing ID on a specific element (div in this case)..
Can't seem to find code sample for this..im using jquery but i dont think i need to do jquery on this one, just basic getElement.. but i need to isolate the search inside a div block.. because the id does exist in other elements on the page but i need to know if it exist in a specific area/div.
so instead of just
document.getElementById(target_id);
i need something like:
divName.getElementById(target_id);
or
$("document.divName").getElementById(target_id);
or
$(".divName").document.getElementById(target_id);
Can't seem to find something that works.
IDs are supposed to be unique and no two elements in page should have same id. You may search some element with some class in div with specific ID.
$('#divId .someClass')
or using find()
$('#divId').find('.someClass')
or using context, jQuery( selector [, context ] )
$('.someClass', $('#divId'))
var mySubDiv = myParentDiv.querySelector("#mySubDivId")
is equivalent to
var mySubDiv = document.querySelector("#myParentDivId #mySubDivId");
// don't forget the space : #myParentDiv#mySubDivId won't work
where querySelector and querySelectorAll are very useful functions, enough for me to avoid using jQuery : they accept any css selector
in real life, using the same Id for different DOM elements often happens.
id's should be unique, you can check for element using:
$(".your_parent_div").find("div#some_unique_id");
you can use it for the getElementsByTagName or ClassName, but ID is unique over document. so doesn't need to do that. better to use a special ID.
and in every id define as a element in javascript and you can just write id's name and use it, like this :
ID.style.color = red;
According to my understanding on your question, You have used two id's with same name when u execute, It takes only first ID so you are asking to take id from the specific div, well that is bad type of coding to use two id for same name instead go for class if want to use same name.
solution for your question is -this ->
var someDiv = document.getElementsByClassName("divName");
var someId = someDiv[0].getElementById("target_id");