I started creating some minor code within my site, and i wanted to do some dynamic creation, so some span tags are created using a javaScript for loop.
In the same code, but a different loop i want to add an Event Listener to the tags.The error i get is the element created is non existent, and i have a few ideas why it's not working, but searching the Web and Stack Overflow gave me no answers.
I've considered putting both for loops into a function and calling that function in a similar fashion jquery works with it's document ready function. But i don't think that will fix the issue
var country = ["is_AmericaN", "is_Europe",
"is_Africa","is_AmericaS","is_Asia","is_Australia"];
var spanInto = document.getElementById("spanSelect");
for(i=0; i<6; i++)
{
var spanMake = document.createElement("SPAN");
spanInto.appendChild(spanMake);
spanMake.className += "spanLanguage" + " " + country[i];
}
The code above creates the elements, the code below tries to call them
var countryClass = doucment.getElementsByClassName("spanLanguage");
for(i=0; i< document.countryClass.length; i++)
{
countryClass[i].addEventListener("click", function(){
var hrDisplay = document.getElementById("selectiveDisplay");
hrDisplay.removeAttribute("id");
hrDisplay.className = "noDisplay";
},false);
}
I expect the working code to, once clicked on any span tag, set the display of the hr tag to block or flex. I dont want to create 5-6 span tags manually, it has to be a dynamic creation.
You are missing the position of the adding class
var spanMake = document.createElement("SPAN");
spanInto.appendChild(spanMake);
spanMake.className += "spanLanguage" + " " + country[i];
Here you are assigning the class after appending it into span, that is wrong you need to assign class before.
var countryClass = doucment.getElementsByClassName("spanLanguage");
for(i=0; i< document.countryClass.length; i++)
{
doucment is document and document.countryClass should be countryClass as you already have the instance of the element
var country = ["is_AmericaN", "is_Europe",
"is_Africa", "is_AmericaS", "is_Asia", "is_Australia"
];
var spanInto = document.getElementById("spanSelect");
for (i = 0; i < 6; i++) {
var spanMake = document.createElement("SPAN");
spanMake.textContent = country[i];
spanMake.className += "spanLanguage" + " " + country[i];
spanInto.appendChild(spanMake);
}
var countryClass = document.getElementsByClassName("spanLanguage");
for (i = 0; i < countryClass.length; i++) {
countryClass[i].addEventListener("click", function() {
var hrDisplay = this;
hrDisplay.removeAttribute("id");
hrDisplay.className = "noDisplay";
}, false);
}
.noDisplay {
display: none;
}
<span id="spanSelect"></span>
<br/>
//click on any of them to replace the class
There are multiple points to be corrected:
There was a type "doucment" in your code.Use "document" instead.
Created elements didn't have any text on it, how will you call click
on element when it is not visible in DOM.
Events are attached to anchors/button not span.
Not sure what you are trying to do by attaching events.
below is the code snippet which works for you when you try to add events on dynamic created elements.Let me know if you need further help
function temp() {
var country = ["is_AmericaN", "is_Europe",
"is_Africa", "is_AmericaS", "is_Asia", "is_Australia"
];
var spanInto = document.getElementById("spanSelect");
for (i = 0; i < 6; i++) {
var spanMake = document.createElement("a");
spanMake.innerHTML = country[i];
spanInto.appendChild(spanMake);
spanMake.className += "spanLanguage" + " " + country[i];
}
}
function attachEvent() {
var countryClass = document.getElementsByClassName("spanLanguage");
for (i = 0; i < countryClass.length; i++) {
countryClass[i].addEventListener("click", function(event) {
console.log("I am called" + event.target);
//var hrDisplay = document.getElementById("selectiveDisplay");
//hrDisplay.removeAttribute("id");
//hrDisplay.className = "noDisplay";
}, false);
}
}
a {
padding: 20px;
}
<body>
<div id="spanSelect"></div>
<div id="selectiveDisplay"> </div>
<button onclick="temp()"> Call Me </button>
<button onclick="attachEvent()"> Attach Event </button>
</body>
Related
The html buttons are created in JavaScript, each with their own ID. They activate the same function when pressed, and I want to know which button is pressed. I use this.id to see the ID of the button pressed. I think, since I haven't retrieved the buttons in JavaScript (eg. button = document.getElementById('button')), it doesn't work. I don't know how to do this with HTML elements created inside the script.
var paragraph = document.getElementById('paragraph');
var cabins = [1,2,3];
for (var i = 0; i < cabins.length; i++) {
paragraph.innerHTML += "Cabin " + cabins[i] + "<br><br><button id='cabin" + cabins[i] +"' onclick='purchaseCabin()'>Purchase</button><br><br>"
}
function purchaseCabin() {
var cabinId = this.id;
console.log(cabinId);
}
<p id="paragraph"></p>
Expected result: the ID of the pressed button is written in the console
Actual result: "undefined" is written in the console
this inside the function refers to Window which does not have the property id, thus you get undefined:
Pass this object to the function so that you can refer that inside the function:
var paragraph = document.getElementById('paragraph');
var cabins = [1,2,3];
for (var i = 0; i < cabins.length; i++) {
paragraph.innerHTML += "Cabin " + cabins[i] + "<br><br><button id='cabin" + cabins[i] +"' onclick='purchaseCabin(this)'>Purchase</button><br><br>"
}
function purchaseCabin(current) {
//console.log(this.constructor.name); // Window
var cabinId = current.id;
console.log(cabinId);
}
<p id="paragraph"></p>
Beginner here. I have a loop that creates 26 buttons with unique ID's and values. What I'm struggling with is figuring out the proper way to send the button's ID to a function so that I can store unique vars for each button independently without creating more than one function. I currently have an array with the 26 items I need for my buttons and the following loop:
function makeButtons() {
for (var i = 0; i < 26; i++) {
document.getElementById("whereButtonsGo").innerHTML += "<input type = 'button' value = '" + items[i] + "' id = 'button" + items[i] + "' onclick = doThing(button" + items[i] + ")'>";
}
}
I want the argument in the onclick function to be sent to a function such as:
function doThing(id) {
document.getElementById("'" + id.value + "'").style.color = "pink";
}
But so far I haven't been able to get this to work. Any help would be greatly appreciated!
Maybe this is what you are looking for:
makeButtons();
function makeButtons() {
for (var i = 0; i < 26; i++) {
document.getElementById("whereButtonsGo").innerHTML += "<input type = 'button' value = '" + i + "' onclick = doThing(this)>";
}
}
function doThing(currentButton) {
currentButton.style.color = "pink";
}
<div id="whereButtonsGo"/>
Try to keep the IDs as simple as possible
I recommend against using innerHTML for creating elements that you actually want to do something. Even if it works, your code will be amazingly unclear. Instead, write code that demonstrates that you're actually creating and adding elements:
var items = [1,2,3,4,5,6];
function makeButtons() {
var container = document.getElementById("whereButtonsGo");
for (var i = 0; i < items.length; i++) {
var button = document.createElement("button");
button.type = 'button';
button.value = items[i];
button.innerText = items[i];
button.id = 'button'+items[i];
button.onclick = doThing;
container.append(button)
}
}
function doThing() {
console.log('click of ' + this.id);
}
makeButtons();
Note that you don't need to pass the id in the function call for the event - the button that was clicked will be available as this.
Here is a fiddle.
JS doesn't display the output
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.id = "div"+i;
divTag.className = "list";
document.getElementById('div'+i).innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
}
Image here
You missed adding the newly created element to the DOM. Example:
document.getElementById("yourDivContainer").appendChild(divTag);
Fiddle:
http://jsfiddle.net/mbpfgm49/
You need to append your div tags to some element (e.g: body), to make text appear on page
// Let's create some sample data
var obj = {
Search: []
}
var currentYear = (new Date).getFullYear();
for (var i = currentYear - 10; i <= currentYear; i++) {
obj.Search.push({
Title: 'Test',
Year: i
})
}
// Here goes your code fixed
for (var i = 0; i < obj.Search.length; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.className = "list";
divTag.innerHTML = obj.Search[i].Title + ' ' + obj.Search[i].Year;
document.body.appendChild(divTag);
}
Yes, you have to add the element to the DOM.
More basically, it is an anti-pattern to construct IDs for elements and use those as the primary means for referring to elements, by means of calling getElementById at every turn. I guess this approach is one of the many lingering after-effects of the jQuery epidemic.
Instead, keep references to elements directly in JS where possible, and use them directly:
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.className = "list";
parent.appendChild(divTag);
^^^^^^^^^^^^^^^^^^^^^^^^^^ INSERT ELEMENT
divTag.innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
^^^^^^ REFER TO ELEMENT DIRECTLY
}
To be absolutely pedantically correct, what you are creating is not a "tag", it's an "element". The element is the DOM object. The "tag" is the div which characterizes the element type.
I'm confused on how to change text content of div with the DOM. When event is triggered, I see that the new text replace the old but it is in a new div. I want to keep it in "transcriptText" to keep all attributes.`How can I do that?
This is my old div with text inside:
var transcriptText = document.getElementById("transcriptText");
these are my new text SPAN elements
var newTranscript = document.createElement("div");
This is how I handle the event
function EventHandler() {
transcriptText.parentNode.replaceChild(newTranscript, transcriptText);
}
Here is the JSFiddle on how it currently works:
http://jsfiddle.net/b94DG/
What you're doing now is creating a new div, newTranscript, which you create by appending a bunch of spans based on the old text. Then in your event handler you replace the old one with the new one. Instead of that, you could still copy the text from the old one, but then clear it and append the children on the old div, replacing line 36 with:
transcriptText.appendChild(newSpan);
To clear the old element, it might work to just set innerHTML to "", or if necessary you could remove all the children with removeChild as described at https://developer.mozilla.org/en-US/docs/Web/API/Node.removeChild
EDIT:
I modified your fiddle to reflect this:
http://jsfiddle.net/b94DG/1/
You can change the innerHTML of transcriptText instead of creating a new div.
var transcriptText = document.getElementById("transcriptText");
var divideTranscript = document.getElementById("divideTranscript");
divideTranscript.onclick = function() {
var sArr = transcriptText.innerHTML.split(" ");
var newInnerHTML = "";
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
var newText = "<span class='highlight' id='word" + i + "'>" + item + " </span>";
newInnerHTML += newText;
}
transcriptText.innerHTML = newInnerHTML;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
var highlight = document.getElementsByClassName("highlight");
for (i = 0; i < highlight.length; i++) {
highlight[i].onmouseover = mouseOverFunction;
highlight[i].onmouseout = mouseOutFunction;
}
};
Here's the fiddle: http://jsfiddle.net/khnGN/
for(var i=0; i<myJSONObject.model.length; i++){
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
create_div.innerHTML = myJSONObject.model[i].model_name;
var assign_innerHTML = create_div.innerHTML;
var create_anchor = document.createElement('a');
document.getElementById('models').appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
}
for ex the myJSONObject.model.length is 2
the output is like this
<div id = 'model_id0'>XXXXX<a> </a></div>
<div id = 'model_id1'>XXXXX<a> </a></div> */
but instead of above the output sholud be like this
<div id = model_id0> <a> xxxxxx</a></div>
<div id = model_id1> <a> xxxxxx</a></div>
how to append it inside of the innerhtml
any one plz reply !!!!
two suggestions:
1.) instead of assigning innerHTML to model_idx div assign the model name to its child a. and 2nd instead of appending it to DOM in every loop do it after completing the loop as to minimize frequent the DOM Update ie by:
objContainer = document.createElement('div');
for(....)
{
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
var create_anchor = document.createElement('a');
create_anchor.innerHTML = myJSONObject.model[i].model_name;
create_div.appendChild(create_anchor);
objContainer.appendChild(create_div);
}
document.getElementById('models').appendChild(objContainer);
I would go along the lines of:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
create_div.id = "model_id" + i;
create_div.innerHTML = "<a>" + model.model_name + "</a>";
models.appendChild(create_div);
}
Unless you specifically need to do something to the anchor itself (other than set its innerHTML), there's no need to create a reference to an element for it. If you do need to do something specific to that anchor, then in that case have this, instead:
EDIT: As per your comment, you DO want to do something to the anchor, so go with this (now updated) option - assuming the anchor will always be a child of the div that has the ID you require. The reason "model_id" + i is being put in as a string is because that is exactly what is being passed into the HTML - the document has no clue what "i" is outside of javascript:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
var create_anchor = document.createElement("a");
create_div.id = "model_id" + i;
create_anchor.innerHTML = model.model_name;
if(window.addEventListener) {
create_anchor.addEventListener("click", function() {
getModelData(1, this.parentNode.id);
}, false);
} else {
create_anchor.attachEvent("onclick", function() {
getModelData(1, this.parentNode.id);
});
}
create_div.appendChild(create_anchor);
models.appendChild(create_div);
}