How to list childNodes names? - javascript

I have some sample website and I want to display the number of child nodes in the entire document and in the body node.
I manage to do it using code:
var childDoc = document.childNodes.length;
alert("Document have " + childDoc + " child nodes");
var childDoc2 = document.body.childNodes.length;
alert("Body have " + childDoc2 + " child nodes");
Now I need to list those nodes names but i dont know how. Can anyone help me?
EDIT.
working solution
var bodyChilds = document.body.childNodes;
var strg = "";
for(var i=0; i < bodyChilds.length; i++){
strg = strg + bodyChilds[i].nodeName + "\n";
}
alert (strg);

Just use simple loop and array index.
You can read more here : ChildNodes
for (var i=0;i<document.body.childNodes.length;i++)
{
//current node in childNodes[i]
}

To get the each childs (tag) name
var bodyChilds = document.body.childNodes;
var tagNames = [];
var localNames = [];
var nodeNames = [];
for(var i=0; i<bodyChilds.length; i++){
// note: tag name will be undefined when is a text node
//Here you can check null/undefined and take decision according to your need
tagNames.push(bodyChilds[i].tagName);
localNames.push(bodyChilds[i].localName) //Name provided by developer in html
nodeNames.push(bodyChilds[i].nodeName)
}
console.log(tagNames);
console.log(localNames);
console.log(nodeNames);

Related

How to change innerHTML of each item in a list of webelements with nested classes

I am trying to make a javascript webextension that adds a couple numbers eg. "123" to the end of the inner text of a hyperlink text to each product on a shopping website, http://www.tomleemusic.ca
for example, if i go to this link, http://tomleemusic.ca/catalogsearch/result/?cat=0&q=piano
I want to add some numbers to the end of each product's name.
name of product and its nested hyperlink
so far, I have attempted the following code but it does not produce any results. Thanks for helping :)
var products= document.querySelector(".category-products, .products-
grid category-products-grid itemgrid itemgrid-adaptive itemgrid-3col
centered hover-effect equal-height");
var productslist = products.getElementsByClassName("item");
for (var i = 0; i < productslist.length; i++) {
productslist[i].getElementsByClassName("product-name").innerHTML =
productslist[i].getElementsByClassName("product-name").innerHTML +
"1234";
}
Your query is wrong and you should use querySelectorAll instead of querySelector for fetching all elements matching the query.
Below is the code required as per given site:
var productsListLink = document.querySelectorAll(".products-grid .item .product-name a:not(.product-image)");
for (var i = 0; i < productsListLink.length; i++) {
var a = productsListLink[i];
var name = a.innerHTML || "";
name += "1234";
a.innerHTML = name;
a.setAttribute('title', name);
}
I guess I found what you needed.
var products = document.querySelector(".category-products .products-grid.category-products-grid.itemgrid.itemgrid-adaptive.itemgrid-3col.centered.hover-effect.equal-height");
var productslist = products.getElementsByClassName("item");
for (var i = 0; i < productslist.length; i++) {
var productName = productslist[i].getElementsByClassName("product-name")[0].firstChild;
productName.innerHTML = productName.innerHTML + "1234";
}

For loop through Array only shows last value

I'm trying to loop through an Array which then uses innerHTML to create a new element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.
window.onload = function() {
// Read value from storage, or empty array
var names = JSON.parse(localStorage.getItem('locname') || "[]");
var i = 0;
n = (names.length);
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
}
I have a UL with the id 'list' in my HTML.
Change your for loop:
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
Use += instead of =. Other than that, your code looks fine.
I suggest you to first make a div by create element. there you add your innerHTML and after that you can do the appendchild. That will work perfectly for this type of scenario.
function displayCountries(countries) {
const countriesDiv = document.getElementById('countriesDiv');
countries.forEach(country => {
console.log(country.borders);
const div = document.createElement('div');
div.classList.add('countryStyle');
div.innerHTML = `
<h1> Name : ${country.name.official} </h1>
<h2> Capital : ${country.capital} </h2>
<h3> Borders : ${country.borders} </h3>
<img src="${country.flags.png}">
`;
countriesDiv.appendChild(div);
});
}

excluding particular elements from onbeforeprint in javascript

I am more familiar with CSS coding than with Javascript, so when I was tasked to find a way to display Link URLS during print but not on-screen, I ran into a bit of trouble. Using CSS, I can manage what I want just fine, but thanks to Internet Explorer's quirkiness, I've had to find a javascript solution to my problem.
I was able to solve my dilemma with this code to make the link URLs display on print, and then disappear off the page when print preview was closed.
window.onbeforeprint = function(){
var links = document.getElementsByTagName("a");
for (var i=0; i< links.length; i++){
var theContent = links[i].getAttribute("href");
if (!theContent == ""){
links[i].newContent = " [" + theContent + "] ";
links[i].innerHTML = links[i].innerHTML + links[i].newContent;
}
}
}
window.onafterprint = function(){
var links = document.getElementsByTagName("a");
for (var i=0; i< links.length; i++){
var theContent = links[i].innerHTML;
if (!theContent == ""){
var theBracket = theContent.indexOf(links[i].newContent);
var newContent = theContent.substring(0, theBracket);
links[i].innerHTML = newContent;
}
}
}
However, now my problem becomes that ALL the page link URLs are printed. But, obviously, I don't need to print things like the internal navigation URLs; that just makes the finished product look messy. Is there a way to exclude certain sections of the page, like a UL-list with the ID of Navigation, from the onbeforeprint/onafterprint functions in javascript?
getElementsByTagName can be used as a method of any DOM node.
Thus:
var links = document.getElementById('showURLs').getElementsByTagName('a');
Using an ID on the parent
Simply replace the variable definition for links in your code with the above. Like so:
window.onbeforeprint = function(){
var links = document.getElementById('showURLs').getElementsByTagName('a');
for (var i=0; i< links.length; i++){
var theContent = links[i].getAttribute("href");
if (!theContent == ""){
links[i].newContent = " [" + theContent + "] ";
links[i].innerHTML = links[i].innerHTML + links[i].newContent;
}
}
}
window.onafterprint = function(){
var links = document.getElementById('showURLs').getElementsByTagName('a');
for (var i=0; i< links.length; i++){
var theContent = links[i].innerHTML;
if (!theContent == ""){
var theBracket = theContent.indexOf(links[i].newContent);
var newContent = theContent.substring(0, theBracket);
links[i].innerHTML = newContent;
}
}
}
Excluding children of a specific element
window.onbeforeprint = function(){
var links = document.getElementsByTagName("a");
var exclude = document.getElementById("navBar").getElementsByTagName("a");
for (var i=0; i< links.length; i++) {
if (!in_array(links[i], exclude)) {
var theContent = links[i].getAttribute("href");
if (!theContent == "") {
links[i].newContent = " [" + theContent + "] ";
links[i].innerHTML = links[i].innerHTML + links[i].newContent;
}
}
}
}
We get an array of all links on the page and one of links in the exclusion element (here with an ID of "navBar"). Then, when we are looping through the links on the page, we first check if they're in the exclusion array, and only if they're not we act!
For that conditional we use the bool in_array(needle, haystack) function, which returns true if the needle is found in the haystack (an array), false otherwise. This function is actually an adaptation of PHP's native function - see PHP manual.
function in_array(needle, haystack) {
for (i=0;i<haystack.length;i++) {
if (haystack[i] == needle) {
return true;
}
}
return false;
}
See this JSfiddle I created to test it. If you run print preview in your browser, you'll be able to see the links on the right!
Hope this helps :)

Why is my Javascript not valid?

I have a div with ID 'adpictureholder', to which I dynamically add (or remove) images.
On Form submit I want to get SRC values of all these images within that DIV and put them to the value of one hidden input with ID 'piclinkslisttosubmit'. The thing is that my current Javascript does not function as if there is some syntax typo there, but I don't see where. Can anyone please have a quick look at it?
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes[].length - 1;
var images = document.getElementById('adpictureholder').childNodes[];
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
Change childNodes[] to simply childNodes.
You don't need to specify that a variable you're referencing is an array by adding brackets.
Your javascript isn't valid because you keep putting childNodes[] you can solve that by replacing childNodes[] with simply childNodes
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
} ​
You shouldn't use [] when reading a property value:
var images = document.getElementById('adpictureholder').childNodes;
You can then get the length from the array, instead of reading the property again:
var endi = images.length - 1;
First off you don't need the [] after childNodes. that causes an error.
You also were forgetting that childNodes includes text nodes and would not work properly, because they did not all contain the src property. I've corrected that in the following example:
function copyonsubmit() {
var str = '';
var textbox = document.getElementById('piclinkslisttosubmit');
var i = 0;
var images = document.getElementById('adpictureholder').childNodes;
var numImages = images.length - 1;
var src = "";
for (i = 0; i < numImages; i++) {
if (images[i].tagName === "IMG") {
str += images[i].src + '|';
}
}
str = str.slice(0, -1); // cut off the final |
textbox.value = str;
}
http://jsfiddle.net/NWArL/2/
Secondly you could write this really simply with jQuery.
var str = "";
$("#apictureholder").children("img").each(function() {
str += $(this).attr("src") + "|";
})
$("#piclinkslisttosubmit").val(str);
Third off make sure to check your console for errors. It was very clear when I ran this code on JSFiddle that it had a problem.
Finally, what exactly are you trying to do?
Change childNodes[] to childNodes and rest looks fine to me,
Read about childNodes
Try,
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
You said you were using jQuery, but you presented us with vanilla Javascript. I took the liberty of converting your code to jQuery and cleaning it up a bit. The others have already identified your problem, though.
function copyonsubmit() {
var strump1 = '';
var images = $("#adpictureholder")[0].childNodes;
for (var i = 0; i < images.length; i++) {
strump1 += '|' + images[i].src;
}
$('#piclinkslisttosubmit').val(strump1);
}​

Get the list of attributes of a HTML string using Javascript

How can I get the list of attributes of an HTML string using Javascript? Here's my code so far.
function traverse_test(){
var root=document.getElementById('arbre0').childNodes;
for(var i=0;i<root.length;i++){
var lis = root[i];
if (lis =='[object HTMLUListElement]') {
for (var member in lis) {
if (typeof lis[member] == "string") {
var assertion = lis[member];
var resultat = assertion.search(/..Bookmarks/);
if (resultat != -1) {
output.innerHTML+= lis[member];
// Here I'd like to have the list of lis[member] attributes
for(var attr in lis[member].attributes) {
output.innerHTML+=lis[member].attributes[attr].name + "=\""+ lis[member].attributes[attr].value + "\"";
}
break;
}
}
}
}
}
}
Use the Node.attributes property of a DOM element. Example:
var foo = document.getElementById('foo'),
attrs = foo.attributes,
i = attrs.length,
attr;
while (i--)
{
attr = attrs[i];
console.log(attr.name + '="' + attr.value + '"');
}
Demo: http://jsfiddle.net/mattball/j8AVq/
Seems like all these answers point to how to get an attr list from a node but the question asks for attrs from an HTML string. Here is my 2cents.
//turn your string into a node and get your html strings NamedNodeMap
var temp = document.createElement("div");
temp.innerHTML = "<div attr-1 attr-2 attr-3 attr-4></div>";
temp = temp.firstElementChild.attributes;
//put the attributes in a an array
var list = Object.keys(temp).map( function( index ) { return temp[ index ] } );
console.log( list );
If you know the attributes to get the value you can do:
var MyValue = document.getElementById("myimage").getAttribute("src")
In JavaScript to loop all attributes:
var el = document.getElementById("someId");
var arr = [];
for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
arr.push(attrs.item(i).nodeName);
}
The above code was taken from this question
Jquery might be another option:
http://plugins.jquery.com/project/getAttributes
[].slice
.apply(document.querySelector('something').attributes)
.forEach(function(item){
console.log(item, item.name, item.value);
});

Categories

Resources