var a = document.getElementsByClassName("lamp");
var b = document.getElementsByTagName("div");
a[0].b[1].style.color = "white";
Why this code is wrong??
Both a and b are nodelists. A language doesnt work how you think it should.
You need to filter the Class Collection by their tagName, than loop trough and add the style ;)
document.getElementsByClassName("lamp").filter(e=>e.tagName=="div").forEach(e=>e.style.color="white";);
However, jquery (a library) is quite useful in such a case:
$("div .lamp").each(function(){
this.css("color","white");
});
Related
I am trying to transition from pure JavaScript to jQuery. I have a for loop that dynamically creates HTML elements with data from an API. Here is my old code:
recipeDiv = [];
recipeDiv[i] = document.createElement("div");
recipeDiv[i].setAttribute("class", "recipeBlock");
recipeDiv[i].appendChild(someElement);
However, when I transitioned to jQuery and used this instead
recipeDiv = [];
recipeDiv[i] = $("<div/>").addClass("recipeBlock");
recipeDiv[i].appendChild(someElement);
I get the following error: recipeDiv[i].appendChild is not a function
I know that .appendChild() isn't jQuery (JS), but shouldn't it still work? Even if I use the jQuery .append() function, I still get an error.
Any help is greatly appreciated.
You seem to be confusing yourself by inter-changing jQuery and DOM APIs. They cannot be used interchangeably. document.createElement returns an Element and $("<div />") returns the jQuery object. Element object has the appendChild method and jQuery object has the append method.
As a good practice, I would suggest you choose between DOM APIs or jQuery, and stick to it. Here is a pure jQuery based solution to your problem
var recipeContainer = $("<div/>")
.addClass("recipeContainer")
.appendTo("body");
var recipeDiv = [];
var likes = [];
for (var i = 0; i < 20; i++) {
//Create divs so you get a div for each recipe
recipeDiv[i] = $("<div/>").addClass("recipeBlock");
//Create divs to contain number of likes
likes[i] = $("<div/>")
.addClass("likes")
.html("<b>Likes</b>");
//Append likes blocks to recipe blocks
recipeDiv[i].append(likes[i]);
//Append recipe blocks to container
recipeContainer.append(recipeDiv[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Maybe someElement is not created? Does the code need to be as follows?
recipeDiv = [];
var someElement = $("<div/>").addClass("recipeBlock");
recipeDiv[i].appendChild(someElement);
Snippet of HTML code I need to retrieve values from:
<div class="elgg-foot">
<input type="hidden" value="41" name="guid">
<input class="elgg-button elgg-button-submit" type="submit" value="Save">
</div>
I need to get the value 41, which is simple enough with:
var x = document.getElementsByTagName("input")[0];
var y = x.attributes[1].value;
However I need to make sure I'm actually retrieving values from inside "elgg-foot", because there are multiple div classes in the HTML code.
I can get the class like this:
var a = document.getElementsByClassName("elgg-foot")[0];
And then I tried to combine it in various ways with var x, but I don't really know the syntax/logic to do it.
For example:
var full = a.getElementsByTagName("input")[0];
So: Retrieve value 41 from inside unique class elg-foot.
I spent hours googling for this, but couldn't find a solution (partly because I don't know exactly what to search for)
Edit: Thanks for the answers everyone, they all seem to work. I almost had it working myself, just forgot a [0] somewhere in my original code. Appreciate the JQuery as well, never used it before :-)
The easiest way is to use jQuery and use CSS selectors:
$(".elgg-foot") will indeed always get you an element with class "elgg-foot", but if you go one step further, you can use descendent selectors:
$(".elgg-foot input[name='guid']").val()
That ensures that you only get the input named guid that is a child of the element labelled with class elgg-foot.
The equivalent in modern browsers is the native querySelectorAll method:
document.querySelectorAll(".elgg-foot input[name='guid']")
or you can do what you have yourself:
var x = document.getElementsByClassName("elgg-foot")
var y = x.getElementsByTagName("input")[0];
Assuming you know it is always the first input within the div
You can combine it like this:
var a = document.getElementsByClassName("elgg-foot")[0];
var b = a.getElementsByTagName("input")[0];
var attribute = b.attributes[1].value;
console.log(attribute); // print 41
Think of the DOM as the tree that it is. You can get elements from elements in the same way you get from the root (the document).
You can use querySelector like
var x = document.querySelector(".elgg-foot input");
var y = x.value;
query the dom by selector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var fourty1 = document.querySelector('.elgg-foot input[name=guid]').value;
querySelector will return the first match from the selector. This selector will find the element with class elgg-foot and then look at the input element inside of that for one named guid and then take the value of the selected element.
I think the simplest way would be using JQuery. But using only javascript,
the simplest way would be:
var div = document.getElementsByClassName("elgg-foot")[0];
var input = div.getElementsByTagName("input")[0];
alert(input.value)
Take a look at this JSFiddle here: http://jsfiddle.net/2oa5evro/
If you were to label elements by some [tag] system, likely attached by the user, and you wanted to count the number of tags (defined by the number of classes the element has), how would you accomplish this?
This could be beneficial if you were to try to review all elements by number of tags. (This likely could be accomplished by other structures, but if you were to only reference the element tags in this way)
Jquery has .hasClass(), is there something like .classCount()
You could create it...
$.fn.classCount = function() {
return $.grep(this.attr("class").split(/\s+/), $.trim).length;
};
jsFiddle.
If you don't have jQuery, you could use...
var classLength = element.classList.length;
jsFiddle.
If you don't have jQuery and have to support the older browsers, go with...
var classes = element.className.replace(/^\s+|\s+$/g, "").split(/\s+/);
var classLength = classes[0].length ? classes.length : 0;
jsFiddle.
You can use the classList attribute if you are using HTML5. For example
$("#someElementId").classList.length
would return 2 for:
<div id="someElementId" class="stinky cheese"></div>
as in http://jsfiddle.net/thegreatmichael/rpdEr/
$(element).attr('class').split(/\s+/).length
jsFiddle example
I've searched quite a bit on both google and stackoverflow, but a lack of knowledge on how to ask the question (or even if I'm asking the right question at all) is making it hard to find pertinent information.
I have a simple block of code that I am experimenting with to teach myself javascript.
var studio = document.getElementById('studio');
var contact = document.getElementById('contact');
var nav = document.getElementById('nav');
var navLinks = nav.getElementsByTagName('a');
var title = navLinks.getAttribute('title');
I want to grab the title attribute from the links in the element with the ID 'nav'.
Whenever I look at the debugger, it tells me that Object #<NodeList> has no method 'getAttribute'
I have no idea where I'm going wrong.
The nodetype and nodevalue for navLinks comes back as undefined, which I believe may be part of the problem, but I'm so new to this that I honestly have no idea.
The getElementsByTagName method returns an array of objects. So you need to loop through this array in order to get individual elements and their attributes:
var navLinks = nav.getElementsByTagName('a');
for (var i = 0; i < navLinks.length; i++) {
var link = navLinks[i];
var title = link.title;
}
Calling nav.getElementsByTagName('a') returns list of objects. And that list doesn't have getAttribute() method. You must call it on ONE object.
When you do:
navLinks[0].getAttribute('title')
then it should work - you will get title of the first matched element.
var navLinks = nav.getElementsByTagName('a');
getElementsByTagName returns multiple elements (hence Elements), because there can be multiple elements on one page with the same tag name. A NodeList (which is a collection of nodes as returned by getElementsByTagName) does not have a getAttribute method.
You need to access the property of the element that you actually need. My guess is that this will be the first element you find.
var title = navLinks[0].getAttribute('title');
I have this HTML-element:
<div class="option default"></div>
...and I try to get to it in Dojo like this:
var el = dojo.query(".option.default");
But when I try:
alert(dojo.attr(el, "class"));
...I get undefined.
Update:
For some reason, this works:
alert(el.attr("class"));
How come the other method doesn't work?
dojo.query() returns a list of DOM nodes based on a CSS selector, not a single element.
You would need to do:
var els = dojo.query(".option.default");
var el = els[0];
alert(dojo.attr(el, "class"));
Here's a working example: http://jsfiddle.net/ArtBIT/L35k6/
Would add to the comment but I can't.
#Orolin, how does Dojo know that you know you're expecting a single Node to be returned. If it special cased single elements then anywhere you call dojo.query() and genuinely don't know how many elements you're expecting to get back, you'd have to test yourself. That would be horrid, and take more than three characters!
If you really want this functionality, just do one of the following:
dojo.queryFirst = function() {
return(dojo.query(arguments)[0]);
}
or, if you must
dojo._oldQuery = dojo.query;
dojo.query = function() {
var nodes = dojo._oldQuery(arguments);
return nodes.length > 1 ? nodes : nodes[0];
}