I have a script
var firstImg = row.getElementsByTagName('img')[0];
and later
if (x){ firstImg.src='/images/checked.png'; }
I'd like to define that the img should be of class='something'
(Get first img with class='something')
The getElementsByClassName() method returns an array-like of objects of the child elements with a specified class name. The getElementsByClassName() method is available on the document element or any other elements. The method returns the elements which is a live HTMLCollection of the matches elements.
The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.
Definition and Usage The getElementsByTagName() method returns a collection of child elements with a given tag name. The getElementsByTagName() method returns a NodeList object.
If you want only the first element in the DOM with that class, you can select the first element out of the array returned. var elements = document. getElementsByClassName('className'); var requiredElement = elements[0]; Else, if you really want to select only one element.
Use the
querySelectorAll('img.classname')[0]
this returns first image with class set to class name. However jQuery is better!!
$('img.classname')
Just set it...
firstImg.className += "something";
...or...
firstImg.classList.add("something");
If you can get away with not supporting older browsers.
Further Reading (disclaimer: link to my own blog).
If you're intending to get elements with a certain class name, you can use...
document.getElementsByClassName("something");
...or...
document.querySelectorAll(".something");
Keep in mind getElementsByClassName()
isn't in <= IE8.
You can use...
var getElementsByClassName(nodeList, className) {
var i, results = [];
for (i = 0; i < nodeList.length; i++) {
if ((" " + nodeList[i].className + " ").indexOf(" " + className + " ") > -1) {
results.push(nodeList[i]);
}
}
return results;
}
Of course, it's super simple if you're using jQuery...
$(".something");
this selects the first img
with class='something':
var firstImg = $('img.something')[0];
If you could not throw away the old browsers, then you need a loop.
var imgs = row.getElementsByTagName('img'),
some_class = 'something',
i, first_img;
for (i = 0; i < imgs.length; i++) {
if ((' ' + imgs[i].className + ' ').indexOf(' ' + some_class + ' ') > -1) {
first_img = imgs[i];
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With