I want to create multiple divs using a for loop which i do it like this
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
divs.className = 'button';
divs.data-id = (data[i]).id; // error
document.body.appendChild(divs);
}
Now my issue is that data-id is required but it pops an error. So how can I define data-id dynamically
I also tried giving the whole div as innerHTML of another div but then it wont render. So how can this be solved??
Use setAttribute() instead:
divs.setAttribute('data-id' , data[i].id);
Also note that hyphens are not allowed in Javascript identifiers, they would be parsed as substraction.
You're looking for divs.setAttribute('data-id', data[i].id);.
If you were trying to read an attribute with a funky character such as that dash in your example, you would access it with brackets instead of dot notation and quote the attribute like so: divs.attributes['data-id']
This should work:
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
divs.setAttribute("id", "btn_id");
divs.setAttribute("class", "btn_class");
divs.setAttribute("data-id", (data[i]).id);
document.body.appendChild(divs);
}
Or use Jquery alternatives:
var newDiv= $('<div/>', { id: 'foo', class: 'tclose'})
for(let i = 0; i < data.length; i++) {
let divs = document.createElement('div');
var attr = document.createAttribute('data-id');
attr.value = (data[i]).id;
divs.setAttributeNode(attr);
document.body.appendChild(divs);
}
Related
I am working on a project where the user decides how many buttons are there, and then each button triggers a different function.
What I have done is: I have an input that asks "Enter the number of buttons" and a "Submit" button. When the "Submit" button is clicked, the value of variable n is set to the user-defined value.
I then have the following code (assuming the user has set n to 10):
for (i = 0; i < 10; i++) {
var x = document.createElement('div');
x.id = i;
x.innerHTML = i;
x.onclick = function() {alert(i)};
document.body.appendChild(x);
}
What I want is, that when div with id i is clicked, the pop-up message says i. But what has ended up happening is, that no matter which div I click, the pop-up message always says 10.
Why is this happening? How to fix this?
The only thing you need to change is the assignment of i inside the for-loop. Use let to define a locally-scoped variable. Also, use textContent instead of innerHTML for simple text. It is recommended to used const/let rather than var.
for (let i = 0; i < 10; i++) {
const x = document.createElement('div');
x.id = i;
x.textContent = i;
x.onclick = function() { alert(i) };
document.body.appendChild(x);
}
By iterating over your NodeList elements, you can take this next approach.
First of all, append all your created divs in your HTML and continue by looping through the elements list by document.querySelectorAll("div")
That way you select all elements and then assign an addEventListener to each one of the items. On your alert function, print this.id and it will return you the number of the id of the element which corresponds to your i index.
It would be the same also if you just put the whole addEventListener function inside the other loop.
I just separated both so you can understand it better.
for (i = 0; i < 10; i++) {
var x = document.createElement('div');
x.id = i;
x.innerHTML = i;
document.body.appendChild(x);
}
let divs = document.querySelectorAll("div");
for(var a= 0; a < divs.length; a++){
divs[a].addEventListener("click", function(){
alert(this.id);
});
}
You can use getAttribute to read the id of the elements. I show you an example:
for (i = 0; i < 10; i++) {
var x = document.createElement('div');
x.id = i;
x.innerHTML = i;
x.onclick = function(e) {
let dataId= e.currentTarget.getAttribute("id")
alert(dataId)
};
document.body.appendChild(x);
}
Explanation:
getAtrribute() returns the value of an html attribute as a string, just enter the name of the attribute in braces to get the value. In this case I entered "id" which is the value we want to retrieve.
Also to get the value of the element where you click I use currentTarget, to accurately retrieve the value of the div that the iteration creates. If you use target, and inside the div you have more elements, this code will generate an error. Therefore, it is important to use currentTarget for this application.
This happen because after the initialisationn the function will look for the value of i which is always 10 (once it has been initialized)
EDIT
As explained by #Mr. Polywhirl in his better answer, you can use let in your for loop to declare your variable locally instead of globally.
To solve your problem you can pass an event to the function (the click event) and the getting your value.
It can be done with either :
The value of the content (as you did with x.innerHTML)
Adding an id to the div and getting this id
Example :
for (i = 0; i < 10; i++) {
var x = document.createElement('div');
x.id = i;
x.innerHTML = i;
x.onclick = function(event) {
alert(event.target.innerHTML) // with the content
alert(event.target.id) // with the id
};
document.body.appendChild(x);
}
I'm trying to remove or replace characters in an element while using appendChild as follow:
var options = from.getElementsByTagName("option");
var to = document.getElementById("target");
to.appendChild(options[i].replace("(A)",""));
I tried various different syntax but no luck. Can someone help? Either JQuery or javascript works for me.
Thanks
I assume you're already in a for loop. If so, use the .text property of the option element, and create a new text node.
to.appendChild(document.createTextNode(options[i].text.replace("(A)","")));
Or better, in the loop append to a string, and create a single node at the end.
var txt = "":
for (var i = 0; i < options.length; ++i)
txt += options[i].text.replace("(A)"), "");
}
to.appendChild(document.createTextNode(txt));
If you actually wanted to append a copy of the element itself, then use .cloneNode(true) instead.
for (var i = 0; i < options.length; ++i) {
var clone = to.appendChild(options[i].cloneNode(true));
clone.text = clone.text.replace("(A)", "");
}
I have an array of class names that I want to search a page for. Then I'd like to find all those elements, grab the text inside, and append it to a div.
var div = document.createElement('div');
div.innerHTML = 'List of names from this page';
document.body.appendChild(div);
var classNameArray = ['user', 'username', 'fullname', 'profile-field', 'author', 'screen-name'];
for (var i = 0; i < classNameArray.length; i++) {
element = classNameArray[i];
getSuggestedAuthors(element);
function getSuggestedAuthors(element) {
var classes = document.getElementsByClassName(element);
var index;
for (var index = 0; index < classes.length; index++) {
var class = classes[index];
var textInsideClass = class.innerHTML;
div.appendChild(textInsideClass);
}
}
}
When I run this, it gives me:
Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist.
I believe the problem is occuring at var textInsideClass = class.innerHTML, because when I remove that, it simply grabs all the classes and appends them to the div. However, I'd like to only get the text inside the class.
Anyone know how to do this without jQuery? I'm injected this hs through Google Chrome's executeScript injection.
Thanks so much!
I think your issue is that appendChild only works with nodes. You might be better off just appending to innerHTML using something along the lines of a.innerHTML += f.innerHTML.
You should also be sure to move the getSuggestedAuthors function out of the loop. It works ok as it is, but it's much better form not to declare functions inside a loop.
If you only need to support chrome then all of the handy methods on the Array.prototype should exist :)
var a = document.createElement('div');
a.innerHTML = 'List of names from this page';
document.body.appendChild(a);
function getSuggestedAuthors(elements) {
for (var d = 0; d < elements.length; d++) {
a.appendChild(document.createTextNode(elements[d].innerText));//append loop items text to a
}
}
['user', 'username', 'fullname', 'profile-field', 'author', 'screen-name'].map(function(cls) {
return document.getElementsByClassName(cls);
}).forEach(getSuggestedAuthors);
I have a webpage that contains ASP.NET panels and JavaScript that gets all of the components in the page:
var items = Sys.Application.getComponents();
I need to get the name/ID of each of the elements in the items variable. I have tried the following code: (but it doesn't work)
for (var item in items)
{
alert(item.name);
}
What attribute of 'item' contains the name/ID? How can I modify the above code to do this?
Use the get_name() and get_id() functions instead.
var items = Sys.Application.getComponents() ;
for( var i = 0 ; i < items.length; i++ ) {
var item = items[i];
var id = item.get_id();
var name = item.get_name();
}
http://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationGetComponentsMethod.aspx
None. item is the key/property so you want items[item].name.
However, if items is an array, using for..in to iterate over it is completely inappropriate. In this case use for(var i = 0; i < items.length; i++) and var item = items[i] inside the loop body.
I know that I can run a line of javascript code after the page loads on an iPad with UIWebView (which is what I am using), but I do not know what I could type to go through and remove all of the tags. I also would like to be able to do this to only certain parts of the page e.g. only remove tags within a certain tag.
You can get all elements by tag name using document.getElementsByTagName(). All links have the tag name a. You can visually remove them by setting their display style to none.
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
To remove elements of a certain tag within a certain tag, just invoke getElementsByTagName() on the element in question. Suppose that you want to hide all links inside a <li> only:
var listitems = document.getElementsByTagName('li');
for (var i = 0; i < listitems.length; i++) {
var anchors = listitems[i].getElementsByTagName('a');
for (var j = 0; j < anchors.length; j++) {
anchors[j].style.display = 'none';
}
}
The element.parentNode.removeChild(element) is also a good one, but it doesn't work nicely inside a standard for loop. You need to loop backwards:
var elements = document.getElementsByTagName('a');
for (var i = elements.length; i-- > 0;) {
var element = elements[i];
element.parentNode.removeChild(element);
}
Update as per the clarified functional requirement: you thus want to replace the link element with a text node representing the link's original content? You can use Node.replaceChild() for this. Here's a kickoff example:
var elements = document.getElementsByTagName('a');
for (var i = elements.length; i-- > 0;) {
var element = elements[i];
var text = document.createTextNode(element.firstChild.nodeValue);
element.parentNode.replaceChild(text, element);
}
Thought I'd post a remove() function to complement BalusC:
function remove(el){
if(el.parentNode)el.parentNode.removeChild(el);
}
Note: If the element doesn't have a parent, it means it is not in the DOM tree.
It also means it will be removed in the GC's (garbage collector) next run (as long as there are no references to it).
If you're going to be doing a lot of dom manipulation, it might be worth it to include jQuery to grab your elements. It'd be a little easier to remove items. Eg.
$(function(){
$('.surrounding_class a').remove();
});
If you want to remove links but preserve their display contents (text, images, etc.) you can insert their childNodes before the links, then remove the link elements:
var removeLinks = function(context) {
var undefined;
if(context === undefined) {
context = document;
}
if(!context) {
return false;
}
var links = context.getElementsByTagName('a'), i, link, children, j, parent;
for(i = 0; i < links.length; i++) {
link = links[i];
parent = link.parentNode;
if(!link.href) {
continue;
}
children = link.childNodes;
for(j = 0; j < children.length; j++) {
parent.insertBefore(children[j], link);
}
parent.removeChild(link);
}
return context;
};
// Use:
removeLinks(document.getElementById('container'));