I have several span elements which begin with the same id as shown below...
<span id="graph_machine"
<span id="graph_human"
<span id="graph_custom"
I would like to access these 3 Span elements as an array in my Javascript function..
var elems = document.getElementsById("graph*");
But getElementsById does not support returning multiple values. Any suggestions? Perhaps using a different function and some wildcard?
Thanks.
Use document.querySelectorAll:
var elems = document.querySelectorAll("[id^=graph]");
That will return a node list of any element with an id attribute whose value starts with "graph".
Try to get all span ID and then check if span ID starts with "graph"
var spans = document.getElementsByTagName("span");
var graphSpans = new Array();
for (var i = 0; i <= spans.length; i++) {
if (spans.id.startsWith("graph")) {
graphSpans.push(spans[i]);
}
}
Since startsWith method is not available in Javascript, so you need to add it to prototype as soon document is ready.
jQuery(document).ready(function() {
if (typeof String.prototype.startsWith != 'function') {
// see below for better implementation!
String.prototype.startsWith = function (str){
return this.indexOf(str) == 0;
};
}
}
If you are using jQuery you can use $( "span[id^='graph_']" )
You could get all spans and then check each ID individually:
var spans = document.getElementsByTagName("span");
var graphSpans = [];
for (var i = 0; i < spans.length; i++) {
if (spans[i].id.substring(0,5) === "graph") {
graphSpans.push(spans[i]);
}
}
http://jsfiddle.net/Sp6sp/
try this with jquery
$("span").each(function(){
console.log($(this).attr('id'));
});
Demo
http://jsfiddle.net/p5k2a/1/
Related
So by using native javascript, how would I go about saying
"if this object has this css class, add this to the title attribute"
document.addEventListener("DOMContentLoaded", function(event) {
if(element.classlist.contains("current_page_item")||element.classlist.contains("current-page-ancestor")){
}
});
That is as far as I've gotten, I'm trying to stick to native javascript just so we don't have to load up any libraries and can keep the site as minimalist as possible.
You can use getElementsByClassName()
var x = document.getElementsByClassName("current_page_item");
Then loop and add title
x.forEach(function(element){
element.title = "title";
});
or
for (var i = 0; i < x.length; i++) {
x[i].title ="title";
}
To answer to your comment, to apply the title to the "a" element that is a child of the div element that has the "current_page_item" class
for (var i = 0; i < x.length; i++) {
var y = x[i].getElementsByTagName("a");
y[0].title = "title";
}
Similar to Rohit Shetty's reply, you could also use the querySelector:
let elements = document.querySelector(".current_page_item");
elements.forEach(function(e) {
e.title = "title";
);
You can use getElementsByClassName()
var x = document.getElementsByClassName("current_page_item");
for(var i=0;i<x.length;i++){
x[i].title += "BLAH";
}
I don't now if I have understood well.
But let's try.
First, locate the elements.
const nodes = document.querySelectorAll('.current_page_item, .current_page_item')
// nodes are the elements of one of the classes names
Then, apply the class Names to title.
function containsOfTheClasses (node) {
return classNames.some(x => node.classList.contains(x))
}
nodes.forEach(function (node) {
node.title += classNames.filter(containsOfTheClasses).join(' ')
})
Is it possible to write a JQuery function that will remove everything with a specific :before content.
here is an example statement to give you something to show me with code:
remove all elements in the document that have a :before pseudo element with content set to "delete me"
Mhh, you can try something like this:
var sheets = document.styleSheets;
var len = sheets.length;
var ba = /:before|:after/;
// Loop throught all stylesheets
for (var i = 0; i < len; i++) {
// work out which method to get the CSS rules
var sheet = sheets[i],
rules = sheet.cssRules || sheet.rules;
// Loop through all rules
for (var r = 0, rule; rule = rules[r++];) {
// if this rule uses one of the test selectors
if (rule.selectorText.match(ba)) {
if (rule.style.content.indexOf('delete me') !== -1) {
var elems = document.querySelectorAll(rule.selectorText.split(':')[0]);
for (var e = 0, elem; elem = elems[e++];) {
// remove the node
document.body.removeChild(elem);
}
}
}
}
}
http://fiddle.jshell.net/6m5kB/1/
there is simple answer just add class on that element with before and remove it through that class. pseudo-element does not exist in dom that why you cannot directly remove them through jquery or js
Is there a way to get multiple attributes in jQuery
<input type="text" title="hello there" class="maiz"/>
(function() {
var inputTitle = $("input").attr("title","class");
console.log(inputTitle[1])//output:undefined
})();
I'm new to jQuery
You can't get multiple attributes, you just have to call attr again:
var input = $("input");
var title = input.attr("title");
var cls = input.attr("class");
Your example sets the value "class" to the title attribute.
Or more similar to your original code:
var inputTitle = [input.attr("title"), input.attr("class")];
inputTitle[1]; // gives you 'maiz'
You can try this:
for (var i = 0; i < elem.attributes.length; i++) {
var attrib = elem.attributes[i];
if (attrib.specified == true) {
console.log(attrib.name + " = " + attrib.value);
}
}
You can get the attributes using the attributes property on the element object:
var el = document.getElementById("someId");
var attributes = el.attributes; // Here they are
In jQuery you can get the Original element with the get() method, like:
var el = $("input").get(0);
var attributes = el.attributes; // Here they are
Try this:
$('.maiz').click(function(){
for(var i = 0;i < this.attributes.length;i++){
console.log(this.attributes[i]);
}
});
Demo
Jquery selector works pretty much like the CSS selector.
$('selector') if you want to select all elements if a particular class
$('.class') if you want to select class and id
$('.class, #id')
that's basically it. unless you have a specific question
I got a li that looks like:
<li temp="true">HELLO</li>
How would I get "temp" so I can manipulate "HELLO" in JS...I know how by id or even className
In supporting browsers (that is, anything except ancient IE):
var li = document.querySelector("li[temp=true]");
If support for older IE is required try this:
var li = document.querySelector ? document.querySelector("li[temp=true]")
: (function() {
var lis = document.getElementsByTagName('li'), l = lis.length, i;
for( i=0; i<l; i++) {
if( lis[i].getAttribute("temp") == "true") return lis[i];
}
return false;
})();
Iterate through all li.
var li = document.getElementsByTagName("li");
var found;
for(var i=0; i< li.length;i++){
if(li[i].getAttribute("temp") == "true"){
found = li[i]; break;
}
}
console.log(found);
OR
You can use native query
var found= document.querySelectorAll('li[temp="true"]');
JSFiddle
In jQuery, you can use the attribute selector:
$('li[temp="true"]');
Alternatively, you can use the document.querySelectorAll() method for a native JS solution. You should be aware of the cross-browser implications of this, however:
var ele = document.querySelectorAll('li[temp="true"]');
You can see a jsFiddle Demo of the above.
As an aside, you should use data- attributes to store custom attributes with HTML elements, for example the correct syntax should be:
<li data-temp="true">HELLO</li>
I used $('#ul li').get() to get all the list elements and stored in an array, each of this list elements have classes...
var i;
var listClass = ('#ul li').get();
for(i=0;i<listClass.length;i++){
var theClass = listClass[i].attr("class"); //<--what's the proper function/method/code for this?
var content = listClass[i].innerHTML; //<-- works very well
//other codes here
}
How may i able to get the classes of each list elements...Thanks!
You can use jQuery's own map to do that:
alert($('#ul li').map(function() {
return this.className;
}).get());
http://jsfiddle.net/MhVU7/
for example. You can do anything with the returned array.
The reason the way you're doing it isn't working is because you're calling the non-existent method .attr on a native DOM element - it's not an extended jQuery object.
var lis = document.getElementById("ul").children;
for (var i = 0, len = lis.length; i < len; i++) {
var li = lis[i],
className = li.className,
value = li.value,
text = li.textContent;
// code
}
The get() method returns a native array of DOM elements, not a jQuery object.
You should use jQuery:
var lists = $('ul li');
var className = lists.eq(i).attr('class');
var content = lists.eq(i).text();
If you want to loop through all the elements
$('ul li').each(function(){
var className = $(this).attr('class');
var content = $(this).text();
});
I have commented the code to better help you understand it.
$("#ul li").each(function() { /* you should only be using # selector to identify id's - if it's all ul's you want just put ul. */
var klass = this.className; /* this refers to the native DOM object, which contains className */
var textContents = this.innerText || this.textContent; /* the text of the list, does not include html tags */
var childNodes = this.childNodes; /* the child nodes of the list, each unencased string of text will be converted into a TextNode */
console.log(klass + ' ' + textContents); /* replace console.log with alert if you do not have a console */
console.log(childNodes);
});
here is an example of the above.
Good Luck!