var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++)
if(test[i].innerHTML().indexOf("search string") != -1){test[i].style.color="black";}
Hopefully it's obvious what I'm trying to do - if there is a link on the page that contains the search phrase, change it's color to black. This isn't working though. Any ideas?
Thanks.
innerHTML is a property not a function, so don't use ().
innerHTML is not a function, it is a property. Try doing this instead:
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++)
if(test[i].innerHTML.indexOf("search string") != -1){test[i].style.color="black";}
A cleaner way of doing it would be to use jQuery:
var searchTerm = 'term1';
$('a').filter(function (a) {
if (this.innerHTML.indexOf(searchTerm) != -1)
return true;
return false;
}).css('color','red')
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++) {
var newElem = test[i].innerHTML;
if(newElem.indexOf("searchString") != -1){
test[i].style.color="black";
}
}
​innerHTML is no function! It's a property!
Related
I'm feeling my way around using JavaScript to populate a HTML5 page - ultimately to link into a Delphi / Datasnap page.
On my page I have a tag setup to provide a listbox as below:
<select id="FirmList" size="10"></select>
I then have a JavaScript script linked to a button that fires on the OnClick
function getJobFirms()
{
var sel = $("#FirmList");
//var sel = document.getElementByID("FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.add(opt);
}
}
The above seems to work - in that Chrome reports no errors and loops through 10 times. However nothing appears in the listbox on the web page, and the length property of sel.option does not increment
I've tried to use other options such as addressing sel.opt directly with no luck
Any suggestions?
You need to use .append()
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
Use
sel.append(opt);
instead of
sel.add(opt);
DEMO
The reason it doesn't work is because sel is a jQuery object, and you're trying to use the native select.add() method, which only works on the native element.
The easy way to fix that would be to do what you seem to have to tried, use getElementById, but you've typed it wrong.
function getJobFirms() {
var sel = document.getElementById("FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.add(opt);
}
}
as you're already using jQuery, you could just do something like this
function getJobFirms() {
$("#FirmList").append(function() {
return $.map(' (. Y .) '.split(''), function(_,i) {
return $('<option />', {text : (i+1), value : i});
});
});
}
Use below jQuery script
function getJobFirms()
{
var sel = $("#FirmList");
//var sel = document.getElementByID("FirmList");
for (var i=0; i<10; i++) {
sel.append('<option value="'+i+'">'+(i+1)+'</option>');
}
}
Here is working JSFiddle
Since you're already using jQuery, you can use the following to make it more readable. As noted in the other questions, add is not a jQuery method and you need to use any variation of append.
function getJobFirms()
{
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
$('<option/>', {text: i + 1, value: i})
.appendTo(sel);
}
}
Demo
Use append();
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.append(opt);
}
OR DEMO JQUERY
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
sel.append($('<option/>',{'text' : i+1},{"value":i}));
//OR
sel.append("<option value='"+i+"'>"+(i+1)+"</option>")
}
I want to get all DIVs in DIV(id = room) and do the same javascript code on each one.
I think it should look like this
Get element by id room -> Get all divs inside -> do something on them(change each class to "grass")
or by using a loop.
How to do that?
Please don't use jQuery.
Modern browsers (IE9+):
var divs = document.querySelectorAll('#room div');
[].forEach.call(divs, function(div){
div.className = 'green';
});
var a = document.getElementById("room").getElementsByTagName("div");
for(i = 0; i < a.length; i++)
{
a[i].className = "grass";
}
Do you want to get all divs inside, or just direct children?
This one traverses direct children. If you want to go through all internal nodes, you need to recurse it.
function grassify(nodeId) {
var node = document.getElementById(nodeId);
for(var i in node.childNodes) {
// Do things with node.childNodes[i], for example:
node.childNodes[i].className = 'grass';
}
}
Then just:
grassify('room');
var room=document.getElementByID("#room");
var divs=room.getElementsByTagName("div");
for(var i=0;i<divs.length;i++){
doSomething(divs[i]);
}
Use getElementByID and getElementsByTagName
Use getElementsByTagName
First get a reference to the container element, then use getElementsByTagName for the type of element you want.
See http://jsfiddle.net/aQtTx/
JS:
var targetDiv = document.getElementById("div1");
var nestedDivs = document.getElementsByTagName("div");
for(var divIndex = 0; divIndex < nestedDivs.length; divIndex++)
{
nestedDivs[divIndex].style.backgroundColor = 'red';
}
function myFunction()
{
var a=document.getElementById('room').childNodes;
for (i=0; i<a.length; i++)
{
a[i].className="grass";
};
}
JsFiddle
var parent = document.getElementById("room");
var divs = parent.getElementsByTagName('div');
for (i=0; i<divs.length; i++)
{
divs[i].className="grass";
};
Is it possible to capitalise the first letter of each word in a certain class name using jQuery / javascript? I just want to capitalise the first letter of each word of all the fields marked with the class 'capital'.
I just want it to do it as they type, and I know you can do it with css but this is no good as it is stored in the DB as lowercase still.
Here's a simple jQuery plugin that could do this for you:
$.fn.capitalise = function() {
return this.each(function() {
var $this = $(this),
text = $this.text(),
tokens = text.split(" ").filter(function(t) {return t != ""; }),
res = [],
i,
len,
component;
for (i = 0, len = tokens.length; i < len; i++) {
component = tokens[i];
res.push(component.substring(0, 1).toUpperCase());
res.push(component.substring(1));
res.push(" "); // put space back in
}
$this.text(res.join(""));
});
};
And then call like:
$(".myClass").capitalise();
Here's a working example.
The solution is something like this:
Working Sample: http://jsfiddle.net/Py7rW/7/
$('.captial').each(function(){
var arr = $(this).text().split(' ');
var result = "";
for (var x=0; x<arr.length; x++)
result+=arr[x].substring(0,1).toUpperCase()+arr[x].substring(1)+' ';
$(this).text(result.substring(0, result.length-1));
});
I think this will work :)
$('.capital').css("text-transform","capitalize");
You can try something like:
$('.capital').each(function() {
var s = $(this).text().split(' ');
for(var i=0; i<s.length; i++) {
s[i] = s[i].substring(0,1).toUpperCase() + s[i].substring(1);
}
s = s.join(' ');
$(this).text(s);
}
I would use the css text-transform:capitalize to avoid having to run this on every keypress,
and change the actual value of the fields on change.
field.value= field.value.replace(/((^| )[a-z])/g, function(a, b){
return b.toUpperCase();
});
Simple Step to capitalize the first letter of each word :
$(document).on('keyup', '#myText', function () {
this.value = this.value.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
});
You could do something like this. This will capitalize the text in a textbox whenever the text has changed:
$(document).ready(function() {
$('.capital').change(function() {
var arr = $(this).val().split(' ');
var result = "";
for (var i=0; i<arr.length; i++){
result += arr[i].substring(0,1).toUpperCase() + arr[i].substring(1);
if (i < arr.length-1) {
result += ' ';
}
}
$(this).val(result);
})
});
You can see a working fiddle here: http://jsfiddle.net/5dMg7/
Is it possible to get an element from the value of the "src" attribute?
There is no DOM method to filter elements by attributes. You need to go through all the elements of a particular tag and filter out those with a matching src value:
function getElementsBySrc(srcValue) {
var nodes = [];
var e = document.getElementsByTagName('img');
for (var i = 0; i < e.length; i++) {
if (e[i].hasAttribute('src') && e[i].getAttribute('src') == srcValue) {
nodes.push(e[i]);
}
}
return nodes;
}
The nodes array will contain all the img elements with a src attribute that has a value image.png.
UPDATE:
Further to the comment below, keep in mind that there might be more than one element with the same src value. That is why the function above returns an array.
You can use the element.setAttribute() method to change the value of an attribute:
var n = getElementsBySrc('old-image.png');
for (var i = 0; i < n.length; i++) {
n[i].setAttribute('src', 'new-image.png');
}
I found some code when google:
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)", "i") : null;
var oCurrent;
var oAttribute;
for(var i=0; i<arrElements.length; i++){
oCurrent = arrElements[i];
oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
if(typeof oAttribute == "string" && oAttribute.length > 0){
if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
arrReturnElements.push(oCurrent);
}
}
}
return arrReturnElements;
}
Source: http://snipplr.com/view/1853/get-elements-by-attribute/
AFAIK (As Far As I Know) there is no native method to get the an element from the value of the src attribute. But using a JavaScript library you can achieve this in one line.
If you use jQuery, you can get the element writing the following code:
var elem = $('[src="path/to/something.xyz"]');
More documentation about this previous code in the jQuery doc.
is it possible to clear all textboxes in HTML by calling a javascript function ?
var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
var fields = document.getElementsByTagName('input'),
length = fields.length;
while (length--) {
if (fields[length].type === 'text') { fields[length].value = ''; }
}
This should do the work
var inputElements = document.getElementsByTagName('input');
for (var i=0; i < inputElements.length; i++) {
if (inputElements[i].type == 'text') {
inputElements[i].value = '';
}
}
If all you fields started blank you can call the form's reset method:
document.forms[0].reset() (there are usually more elegant ways to get the form handle depending on your specific case).
While not the simplest solution, look into jQuery. You should be able to do something like:
$("input[type=text]").val('');
I'm no jQuery expert, though.
I think
$("input:text").val("");
Should work with jQuery.
Old post..but, with jquery for example:
$("input[type=text],textarea,input[type=email]").val('');