Copy innerHTML to clipboard from multiple <li> elements - javascript

I'm trying to create a greasemonkey script to copy the innerHTML of some <li> elements, but I'm unable to to so because it is a nodelist.
var list = document.querySelectorAll(".bx li");
GM_setClipboard(list.innerHTML)

Iterate and generate the combined result.
var list = document.querySelectorAll(".bx li");
GM_setClipboard(
// convert nodelist to array
// for older browser use [].slice.call(list)
Array.from(list)
// iterate and get HTML content
.map(function(e) {
return e.innerHTML;
})
// combine the HTML contents
.join('')
)
Alternatively, we can use simply for loop which would be better since we don't need to create an extra array.
var list = document.querySelectorAll(".bx li");
// initialize string variable for HTML
var html = '';
// iterate over the nodelist using for loop
for (var i = 0; i < list.length; i++) {
// append the HTML content to the string variable
html += list[i].innerHTML;
}
GM_setClipboard(html);

You need to walk through the list and compose required HTML string:
var list = document.querySelectorAll(".bx li");
var html = "";
for(var n = 0; n < list.length; ++n)
html += list[n].outerHTML;

Related

javascript parse text from <a href> links

Lets say I have
ThisTextChanges
ThisTextChanges
ThisTextChanges
ThisTextChanges
I want to iterate through these and get the "ThisTextChanges" which are some numbers that changes, most accurately timers.
How can i achieve that? jquery is fine.
They are inside a div with id "main_container".
I need to put the text in a var so the href is importanto to know which var i use for each one.
Lets break the task down into several steps:
Get a handle to all of our links (document.querySelectorAll)
learn how to get the current text of an a tag (childNode[0].nodeValue)
put it all together (Array.from, Array.map)
Get a handle to all of our links:
we will use document.querySelectorAll to get list of all nodes that match our selector. here I'm just going to use the selector a, but you probably have a class that specifies these links vs other links on the page:
var links = document.querySelectorAll('a');
Get the text of a link
This one is a bit more complicated. There are several ways to do this, but one of the more efficient ways is to loop through the child nodes (which will mostly be text nodes), and append the node.nodeValue for each one. We could probably get away with just using the nodeValue of the first child, but instead we'll build a function to loop through and append each.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
Put it all together
To put it all together we will use Array.map to turn each link in our list into the text inside it. This will leave us with an array of strings. However in order to be able to pass it to Array.map we will have to have an array, and document.querySelectorAll returns a NodeList instead. So to convert it over we will use Array.from to turn our NodeList into an array.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
var linkTexts = Array.from(document.querySelectorAll('a'))
.map(getText);
console.log(linkTexts);
this is text
this is some more text
You can just add condition in the a selector as follows:
var array = [];
$('#main_container a[href="/example2"]').each(function(){
array.push($(this).html());
});
console.log(array);
You can iterate and store them in an Array
var arr = [];
$("a").each(function(){
arr.push($(this).text());
console.log( arr );
});
you can achieve that in may ways. this example using for loop.
var main_container = document.getElementById("main_container");
var items = main_container.getElementsByTagName("a");
for (var i = 0; i < items.length; ++i) {
// do something.....
}
var array = [];
$('#main_container a').each(function(){
array.push($(this).html());
});
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_container">
ThisTextChanges 1
ThisTextChanges 2
ThisTextChanges 3
ThisTextChanges 4
</div>
Please try:
$('#main_container > a[href]').each(function() {
var tes = $(this).attr('href').substring(1);
window[tes] = $(this).text();
});
123 will produce var named example1 with value 123, and so on.

Access table.id in JavaScript

I have a webpage, which has a number of ASP.NET tables.
The tables are defined on the server as follows (id is unique for every table):
dim tblOutput as table
tblOutput.ID = id
I am trying to loop through all the tables on the webpage using JavaScript on the client as follows:
var trs = document.getElementsByTagName("table");
for (var i = 0; i < trs.length; i++) {
var res2 = trs[i].attributes("id")
alert(res2[i].id)
}
The alert always prints 'undefined'. I have debugged using firefox and id is always empty (""). What am I doing wrong?
var res2 = trs[i].attributes("id")
alert(res2[i].id)
You assign a single string to res2 and then you use res2 like it's an array in your alert. You then try and get the id from a string? Not sure what you're trying to do there... Additionally, attributes is not a function, you can access the id with .id.
var tables = document.getElementsByTagName("table");
for (var i = 0; i < tables.length; ++i) {
var id = tables[i].id;
alert(id);
}

Dynamically generating lists without document.write?

I'm using JavaScript to create a list of links from a text source. Using document.write(), resets/creates a new page which is not desirable. I do not know the amount of items in the list, so precomposing a list and using innerHTML to set values doesn't seem 'do-able' ? How would one go about generating dynamic lists in JS?
You can create elements dynamically by using document.createElement. It could work for example like this:
var container = document.getElementById('my-list'),
items = [],
addItem;
addItem = function (text) {
var elm = document.createElement('li');
elm.innerHTML = text;
container.appendChild(elm);
items.push(elm);
};
// generating random list
var i = 0,
j = Math.floor(Math.random() * 50);
for (i; i < j; i++) {
addItem('list item ' + i);
}
As Matti Mehtonen stated you can use document.createElement(), in order to create dynamically elements. One note on this is that instead of appending the newly created elements directly into a DOMnode, you should instead create a document fragment and append the elements to it, afterwards you append the fragment to the DOMnode. This way the process will be faster.
var items = ['cars', 'toys', 'food', 'apparel'];
function render(elementId, list) {
//getting the list holder by id
var el = document.getElementById(elementId);
//creating a new document fragment
var frag = new DocumentFragment();
//iterate over the list and create a new node for
//each list item and append it to the fragment
for (var i = 0, l = list.lenght; i < l; i++) {
var item = document.createElement('span');
frag.appendChild(item.innerHTML = list[i]);
}
//finally append the fragment to the list holder
el.appendChild(frag);
}
//rendering
render("my-list-holder", list);

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>";
}

JavaScript/jQuery: How do I get an array of all attributes in an XML element?

Given an XML element in jQuery like so:
$('<foo oy="vey" foo="bar" here="is" another="attribute" />')
Can I use either jQuery or plain old JavaScript to get an array containing the names of all the attributes in an XML element? I would expect this:
['oy','foo','here','another']
The jQuery function isn't really meant to parse XML, it can parse HTML, but it's not really the same.
What about using the browser's XML parser:
function parseXML(text) {
var parser, xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
} else { // IE
xmlDoc= new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(text);
}
return xmlDoc;
}
// Demo
var doc = parseXML('<foo oy="vey" foo="bar" here="is" another="attribute" />');
var foo = doc.childNodes[0];
for (var i = 0; i < foo.attributes.length; i++) {
var attr = foo.attributes[i];
alert(attr.name + " = " + attr.value);
}
Run the above code here.
This plugin will help you do that.
You can also do it using plain old javascript using something like that :
var elt = document.getElementsByTagName('id');
for (i=0;i<elt.attributes.length;i++){
//elt.attributes[i].nodeName is what you want, .nodeValue for its value.
}
A) Single <Foo> element
Do you need list of attributes of a single element?
... if so - do you really need an array?
Simple $('<foo ... />').get(0).attributes
...will give you NamedNodeMap (object) of attributes
B) All elements <Foo> in the whole (XML) document
#Soufiane Hassou 's answer is showing approach but is missing the inner loop...
Do you need to fetch all possible attribute names of an element (e.g. Product element) inside a whole XML document?
var yourElements = document.getElementsByTagName('Foo'); //get all <Foo> elements
var listOfAttributeNames = []; //prepare empty array for attribute names
var attributeNameBuffer; //buffer for current attribute name in loop
//Loop all elements
for(var i = 0; i < yourElements.length ; ++i){
//Loop all attributes of a current element
for( k = 0 ; k < yourElements[i].attributes.length ; ++k ){
//Temporary store current attribute name
attributeNameBuffer = yourElements[i].attributes[k].name;
//First,
//test if the attribute name does not already exist in our array of names
if( listOfAttributeNames.indexOf(attributeNameBuffer) == -1 )
listOfAttributeNames.push( attributeNameBuffer ); //if not, add it
}
}
console.log(listOfAttributeNames); //display array of attributes in console

Categories

Resources