Javascript get Element in LI tag - javascript

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>

Related

Using Native JavaScript, change the title attribute of an object if it has a certain CSS class

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(' ')
})

find div in html with javascript and regex

I try to select html element with javascript without! jQuery...
for example my html is:
<div id="my1231">
</div>
and i want to select any first div with id started with my, and i try so:
var regex = /my(.*)/;
var templateCode = document.match(regex)
alert(templateCode);
but nothing happend, what i do wrong?
how to select div with regex, where first part of id is static, and second random?
How about document.querySelectorAll?
document.querySelectorAll("[id^='my']")
Just be aware of the >= IE8 support
http://caniuse.com/#search=querySelectorAll
If you really want to use regex to match against ids, you must first get a node list and then loop through it and check each id individually. You can then append each matching element to a new array:
var divs = document.getElementsByTagName('div');
var regex = /my(.*)/, matches = [];
for(i=0; i< divs.length; i++){
if(regex.test(divs[i].id)){
matches.push(divs[i]);
}
}
JSFiddle
Of course you can always mix both answers and use feature detection to determine which method to use:
var divs;
var matches = [];
var re = /^my\w+/;
if (document.querySelectorAll) {
matches = document.querySelectorAll("[id^='my']");
} else if (document.getElementsByTagName) {
divs = document.getElementsByTagName('div');
for(i=0, iLen=divs.length; i<iLen; i++){
if (re.test(divs[i].id)) {
matches.push(divs[i]);
}
}
}
HTH.

Javascript : How to get multiple span elements by ID?

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/

Get list elements and its classes using jquery

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!

Want to set li innerHTML of ul

I'm writing a javascript function where I get a ul object from my HTML and want to set the text of one of the li elements in theul`. I'm doing:
list = document.getElementById('list_name');
Then I want to access the ith li element of list using a loop.
I have:
for (i = 0; i < 5; i++) {
list[i].innerHTML = "<a>text</a>";
}
but this is not working. What is the proper way to do it?
You need to access the child li elements of the ul. JavaScript and the DOM API can't automagically do that for you.
var list = document.getElementById('list_name'),
items = list.childNodes;
for (var i = 0, length = childNodes.length; i < length; i++)
{
if (items[i].nodeType != 1) {
continue;
}
items[i].innerHTML = "<a>text</a>";
}
You could also use getElementsByTagName('li') but it will get all descendent li elements, and it seems you want only the direct descendants.
You could also avoid innerHTML if you want.
var a = document.createElement('a'),
text = document.createTextNode('text');
a.appendChild(text);
items[i].appendChild(a);
innerHTML can cause issues, such as lost event handlers and the performance issue of serialising and re-parsing the HTML structure. This should be negligible in your example, however.
jQuery Sample code, although the others work:
$("#list_name li").text("<a href=''>text</a>");
Its much more succinct with jQuery
You can try the following
var el = document.createElement("li"),
content = document.createTextNode("My sample text"),
myUl = document.getElementById("ulOne");
el.appendChild(content);
el.id = "bar";
myUl.appendChild(el);
Here's the demo: http://jsfiddle.net/x32j00h5/
I prefer a aproach using getElemenetByTagName, if somehow you get a extra node like a script tag or a span you will have problems. A guess this code will help you:
var list = document.getElementById("mylist");
var items = list.getElementsByTagName("li");
for(var i = 0, size = items.length; i< size; i++){
items[i].innerHTML = "<a href='#'>LINK</a>";
}

Categories

Resources