I've got a bit of jQuery that outputs some HTML to an id, however in my code it must output to a class. Any ideas how I can achieve this?
document.getElementById("content").innerHTML=output;
<div class="content> </div>
I've tried getElementsByClass but it doesn't seem to work for me.
What you have there isn't jquery, it's raw JS and if you already have jQuery in your project, it's a bit easier with jQuery:
$(".content").html(output);
Use the getElementsByClassName method.
[0] is missed in the javascript. Thats the reason , you are not able fetch the records.
document.getElementsByClassName("content")[0].innerHTML = output;
getElementsByClassName returns an array of all matching elements. Try looping through this array and adjusting each array item
var elements = document.getElementsByClassName('class-name');
for ( var i = 0; i < elements.length; i++ )
{
elements[i].innerHTML = output;
}
getElementsByClassName returns an array, so assuming this is the first content in your document, use:
document.getElementsByClassName("content")[0].innerHTML = output;
If there are more than one element, you'd use a loop to loop through them and target the element you wish, e.g
var content = document.getElementsByClassName('content');
for (var i = 0; i < content.length; i++) {
content[1].innerHTML = "Second element with class content";
content[3].innerHTML = "Fourth element with class content";
}
jsFiddle here
You can use querySelectorAll for this purpose
document.querySelectorAll(".content")[0].innerHTML = output;
documet.querySelectorAll returns the elements with matching selectors.
Related
I want to change the color of all elements with class='nav-button' using JS. I've tried the code below, but it doesn't seem to work. I think it doesn't recognize 'style' in the 4th line. Not sure why, I've seen plenty of examples where people use it.
var elements = document.getElementsByClassName('nav-button')
for (i = 0; i < elements.length; i++) {
elements[i].firstChild.style.color = 'red';
}
Any solutions?
Edit: the first child item is necessary because there is an element inside of the nav-button
I don't think you need firstChild as the code below worked for me.
var elements = document.getElementsByClassName('nav-button')
Array.from(elements).forEach(el => el.style.color = 'red')
The getElementsByClassName function returns an HTMLCollection instead of an array, so you can't iterate through it. You can achieve it by spreading the collection values in an array, like this:
[...elements]
And then you can use it like this: [...elements].forEach(el => el.style.color = 'red')
Assuming you want to change the color of the firstChild of each element with class nav-button, try using firstElementChild instead of firstChild:
var elements = document.getElementsByClassName('nav-button')
for (let e of elements) {
e.firstElementChild.style.color = 'red';
}
You can iterate on the collection and you don't need to use a variable for that:
for (let el of document.getElementsByClassName('nav-button')) {
el.style.color = 'red'
}
I don't know if you have a purpose using "firstChild" or maybe you copy pasted from somewhere.
But, simply you have to remove firstChild on line 4!
const elements = document.getElementsByClassName('nav-button');
for (let i = 0; i < elements.length; i++) {
elements[i].style.color = 'red';
};
<button class="nav-button">1</button>
<button class="nav-button">2</button>
<button class="nav-button">3</button>
I am using querySelectorAll property initially to obtain nodelists of certain tags,and then from this nodelist i am iterating through each node looking for a certain match to an id property using querySelector,however the result always is null.
var x=document.body.querySelectorAll("script");
for(var i=0;i<x.length;++i)
{
var y=x[i].querySelector("#myid");
console.log(y);
if(y!== null)
{
console.log(i+1);
}
}
i always get an output of null,please help.
If you want to select for example script tags that have the name attribute equal to myName use this:
var elems = document.querySelectorAll('script[name = "myName"]');
You can put as many CSS selectors as ou want to narrow the search.
If you want for example to select div elements that are direct children of li element, and that have the attribute name begin with "abc" and that have an id and a class someClass then use this:
var elems = document.querySelectorAll('li > div[name ^= "abc"][id].someClass');
Here is link to all CSS Selectors!
Krishna your querySelectorAll will grab a nodelist for you. There is no reason for you to add an additional query selector within your loop.
var myId = document.querySelector('#myid');
var collection = document.body.querySelectorAll("script");
for (var i = 0; i < collection.length; i++) {
if (collection[i].includes(myId)) {
console.log(i+1);
}
}
I am currently having problem with selecting and matching the innerHTML using querySelectorAll.
Here is what i did:
document.querySelectorAll('*[class^="js-display-url"]').contains('product')
What the html is:
<span class="js-display-url">product/poss/newslanges</span>
But i want to match the class js-display-url starting with product but can't do that. please help.
With DOM selectors you cannot select elements based on the inner HTML, but you can loop through all the elements with that class and single out the ones that match your condition:
var allElements = document.querySelectorAll('*[class^="js-display-url"]');
var myElements = [];
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].innerHTML.startsWith('product')) {
myElements.push(allElements[i]);
}
}
There isn't a DOM selector which will filter based on text nodes, but you can filter using some array methods, since a NodeList is array-like.
In particular, Array.prototype.filter can get the elements that meet your criteria.
var filter = Array.prototype.filter;
var allElements = document.querySelectorAll('.js-display-url');
var productElements = filter.call(allElements, function(element) {
return element.innerText.startsWith('product');
});
console.log(productElements);
<span class="js-display-url">product/poss/newslanges</span>
I would like to get all the elements/nodes in an HTML page which contain attributes that start with something (again, the attribute names start with something, not their values!). For example, TinyMCE has a tendency of adding custom attributes to the elements it saves, like "mce_style", "mce_href", "mce_bogus", etc. I would like to have something like the CSS3 selector for attribute values, [attr^="mce_"], but not for the values, the attribute names.
Of course, I can iterate through all DOM nodes and their attributes and check them one by one, but I was wondering whether there is a more efficient way.
Please don't give me TinyMCE-specific answers, I'm pretty sure there's a flag which would prevent TinyMCE for saving these attributes, but the question is generic.
here's a simple demo to find all elements that contain an attribute starting with mce_. might need some refinements.
function getMCE() {
var el, attr, i, j, arr = [],
reg = new RegExp('^mce_', 'i'), //case insensitive mce_ pattern
els = document.body.getElementsByTagName('*'); //get all tags in body
for (i = 0; i < els.length; i++) { //loop through all tags
el = els[i] //our current element
attr = el.attributes; //its attributes
dance: for (j = 0; j < attr.length; j++) { //loop through all attributes
if (reg.test(attr[j].name)) { //if an attribute starts with mce_
arr.push(el); //push to collection
break dance; //break this loop
}
}
}
return arr;
}
console.log(getMCE())
Try this:
FUNCTIONS
//custom selector expression
$.extend($.expr[':'],{
attr:function(o,i,m){
var attrs=$.getAttrAll(o),re=m[3],found=false;
$.each(attrs,function(k,v){
if(new RegExp(re).test(v)) { return found=true;}
});
return found;
}
});
// get all atrributes of an element
$.getAttrAll=function(el){
var rect = [];
for (var i=0, attrs=el.attributes, len=attrs.length; i<len; i++){
rect.push(attrs.item(i).nodeName);
}
return rect;
};
`
USAGE
// calling custom selector expression :attr(regexp)
$(function(){
$('body').find(':attr("^mce_")').css({background:'yellow'});
});
HTML
<body>
<p mce_style="height:50px" id="x" data-hello="hello">selected</p>
<div not_mce_bogus="abc">not_mce_bogus</div>
<div mce_href="http://rahenrangan.com">selected</div>
<p>othrs</p>
</body>
One option, if you don't mind temporarily altering your DOM, is to extract your HTML into a string and search for the attributes via RegExp. When you find the attributes, you could append a "needle" in the DOM so that you can use jQuery to select the elements.
Here is a working concept (run with console open):
http://jsfiddle.net/skylar/N43Bm/
Code:
$.fn.extend({
findAttributes: function(attribute) {
var attributeFinder = new RegExp(attribute + '(.+)="', "gi");
var elementHTML = this.html().replace(attributeFinder, "data-needle='pin' "+attribute+"$1=\"");
this.html(elementHTML);
return this.find("[data-needle=pin]").removeAttr('data-needle');
}
});
console.log($("body").findAttributes('mce_'));
Note: my regexp is not great. You'll have to take better care than I have in this example.
Try this: (I tried putting * instead of a tag but it colored all the elements including those who do not have mce_style attribute as well)
a[mce_style] { color : red; }
Demo : http://jsfiddle.net/Tcdmb/
More info : https://developer.mozilla.org/en/CSS/Attribute_selectors
I need to get the text that is inside a element.
I can only grab the class of this element and NOT the ID.
<span class="fileName">test.png</span>
So I need a way to get test.png, but as you see I have only the class of the element and not the ID.
Just notice also that we may have more <span class="fileName"></span>, so it could look like this
<span class="fileName">test1.png</span>
<span class="fileName">test2.png</span>
<span class="fileName">test3.png</span>
<span class="fileName">test4.png</span>
In the case we have more, like the example above, I need to get ALL the values and not only one, because I need to pass this value to another page with jQuery. So it should be able to get one value or more from that element.
Please help!
And also I am not a javascript expert!
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get();
The array filenames will contain all the names of the images. You can pass on this array to another jQuery function, or anywhere else you like to do so.
You can test it here »
Update
Since you request the filenames to be a string separated by a comma, you can do it like this:
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get().join(',');
Now, filenames will contain the string test1.png,test2.png,test3.png,test4.png.
Use document.getElementsByClassName: http://jsfiddle.net/pCswS/.
var elems = document.getElementsByClassName("fileName");
var arr = [];
for(var i = 0; i < elems.length; i++) {
arr.push(elems[i].innerHTML);
}
alert(arr);
(Since you didn't tag the question with jQuery I assume you have to do it with plain JavaScript.)
$('span.fileName').each(function() {
var fileName = $(this).text();
doSomethingWithFileName(fileName);
});
Here the span.fileName selector returns all spans with class fileName then we iterate through, reading the text from each one. You may want to find a container element first and then only iterate inside that, e.g.
var $container = $('#myFileNames');
$container.find('span.fileName').each( ... );
Here's my take:
var spans = document.getElementsByClassName('fileName');
var values = [];
for(var i = 0; i < spans.length; i++) {
values.push(spans[i].innerHTML);
}
// Example of processing: alert the values
alert(values);
Use the following jQuery selector
$("span.fileName").html()