I'm having trouble doing a function in javascript
like she takes the form data and lists it below
I'm doing it this way
<pre>
> function changeText2 () {
> var assembly = ['staff', 'description']
> var node = document.createElement ("LI");
> var textnode = document.createTextNode (assembly);
> node.appendChild (textnode);
document.getElementById ("demo"). appendChild (node);
</pre>
only it returns only ids "staff" and "description"
I want you to take several input
An example
what pretty much what I want you to do is this
only with several campuses
Change it to something like this below. Don't forget to modify HTML accordingly as written in JSfiddle link
const list = document.getElementById('demo');
const changeText2= () => {
let staff = document.getElementById('staff').value;
let desc = document.getElementById('desc').value;
let node = document.createElement ("LI");
let textnode = document.createTextNode(`${staff}, ${desc}`);
node.appendChild (textnode);
document.getElementById ("demo"). appendChild (node);
}
https://jsfiddle.net/1gjs789f/
To expand on your code, first you didn't specify whether you want inputs taken from the fields specified within HTML DOM. You do that by separately calling getElementById on specific fields (in this case, 'staff' and 'desc', as per your code example) and call .value function on them to get the value from the fields.
After that, configure the text that will be displayed inside the LI element.
Using `` and ${} constructions of ES6 as in my example its quite easy, but you can as well use the example below if you find it easier. I may argue it's indeed easier on the eyes, even though I prefer ES6 way.
let textnode = document.createTextNode(staff + ", " + desc);
Finally, append the text node, then append the li element. Done.
Related
I am writing a JS, HTML, DOM script ( using Tamper Monkey ) for an ancient website.
The idea is to use bootstrap and format some tables & lists.
These tables, lists etc have no class, id or anything.
So I grab it by tag name and add class name to it.
I could only select 1 tag instance at a time.
Example
document.getElementsByTagName('ul')[0].className = 'list-group';
('ul')[0] gives first instence.
It does not work on just ('ul').
I want to grab every instance of ul at once.
note: I tried document.querySelectorAll('ul').className = '';
Not working. I want to give all ul same class name.
You need to transform the result for querySelectorAll into an array and apply a forEach function on it:
const elementsCollection = document.getElementsByTagName('ul')
const elementsArray = Array.from(elementsCollection)
elementsArray.forEach(el => el.className = 'foo')
Or, if you want to use querySelectorAll:
const elementsArray = document.querySelectorAll('ul')
elementsArray.forEach(el => el.className = 'foo')
This front-end JavaScript code works, it creates li itens in a ol tag from a list of string data. I would like to do it in just one line...
qelements.map(element => { let litag = document.createElement("li");
litag.innerHTML = element;
oltag.appendChild(litag) });
But this one I get an error: "qlist.html:32 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'."
qelements.map(element => oltag.appendChild(document.createElement("li").innerHTML = element));
Taking out the ".innerHTML = element" it creates empty li elements inside a ol tag as expected
This:
document.createElement("li").innerHTML = element
is an assignment expression. Its resulting value is going to be whatever is on the right hand side of that equals sign (which I'm assuming is a string).
So when you do this:
qelements.map(element => oltag.appendChild(document.createElement("li").innerHTML = element));
You are essentially passing element to appendChild and abandoning the newly created li element, which isn't what you want to do.
If you want to avoid having multiple lines in that particular part of your code, you can factor out a function for creating the li:
function makeLi(content) {
let litag = document.createElement("li");
litag.innerHTML = content;
return litag:
}
Then use it:
qelements.forEach(element => oltag.appendChild(makeLi(element)));
Note also that you seem to be abusing the map() method. If you just want to iterate over a series of values and do something with each one, use .forEach or for .. of.
In my opinion:
You should use snake_case or CamelCase for naming your variables. (qelements -> qElements or q_elements
You should write simple, easy to understand code, not combining complex codes. If you are in a team and you do this, you will kill every one else, they will have a hard time understand what you are writing. Even if you come back and read these codes after a long time, you will not understand yourself.
In this case you can create a helper function to make it one line:
const createLiTagWithText = text => {
const li = document.createElement("li");
li.innerHTML = text;
return li;
}
qElements.map(element => oltag.appendChild(createLiTagWithText(element)));
oltag.appendChild(document.createElement("li").innerHTML = element)
This passes the return value of the assignment expression to appendChild, in other words, it's the same as oltag.appendChild(element). The first version is already pretty much the most readable way to do it.
When I do this:
var elem = $(".region_box");
text = elem.find(".my_text").html();
I can get text from the first element deep below "elem" with class "my_text" which it finds.
But there are many elements of the class "actual_text" below elem and I want to combine the text from all of them. How would I do it?
I am new to jQuery and I searched around for solution for long time, but neither of them worked for me. Perhaps I am using this each() function incorrectly. I would very much appreciate any help.
You can use the jQuery.each
var text = '';
var elms = $(".region_box .my_text").each(function () {
text = text + $(this).text(); // use .html() if you actually want the html
});
Define a variable to hold the new string, select all of the elements you wish to extract, chain that with .each() and add the contents of the text node for that element to the variable you created to hold the new string.
(Demo)
var text = "";
$(".region_box .my_text").each(function(){ text += " " + $(this).text(); });
try something using jquery .map() method like this,
text = $('.region_box').find('.my_text').map(function() {
return $(this).text();
}).get().join(',');
As the site said, "As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array."
Is there a way to find out whether a HTML-tagName comes in pair or alone (Standalone-Tag)?
E.g. <div></div>, <em></em>, <p></p>, ... they come in pair, but <br/>, <input>, <area> ... are Standalone.
I need a function which should find out if a HTML-Code snippet is entered correct. Therefore the function has to investigate among others which HTML-Element can be created with Standalone-Tag.
Do you have any idea how can I find out if an HTML element is standalone? Except for example
something like this:
var myArray = [ list of Standalone-Tags ];
if(jQuery.inArray("test", myArray) != -1 ) { ... }
Thanks.
Browsers don't have a built in list of elements which are defined as empty.
You're most reliable bet would be to create one manually by reading the HTML specification.
Alternatively, you could create an element and see what the browser returns when you convert it to HTML.
var element = prompt("What element name? e.g. br");
var container = document.createElement('div');
var content = document.createElement(element);
container.appendChild(content);
var reg = new RegExp("/" + element);
alert(reg.test(container.innerHTML) ? "Not Empty" : "Empty");
I am trying to parse some elements of a form.
I have with me the form ID/form name.
Now I want to parse through all radio buttons with name= "radio123"(or id="radio123").
But when I try $(this).html on each element (of a radio button)... then I get a blank value...
How do I access the HTML code for all radiobuttons/checkboxes within a form?
This is the normal behavior for jQuery.fn.html function: This method uses the browser's innerHTML property. Look at the examples if you don't understand what I mean.
I don't know why you want to get the HTML (if you want the value, look at the jQuery.fn.val method), but here's a solution
$("input:radio").each(function () {
console.log( this.outerHTML );
});
Be careful with the outerHTML, as it is not supported across all browsers you could use this function:
function getOuterHTML( node ) {
var parent = node.parentNode,
el = document.createElement( parent.tagName ),
shtml;
el.appendChild( node );
shtml = el.innerHTML;
parent.appendChild( node );
return shtml;
}
// use it like getOuterHTML( this ) in the preceding each loop
Something like this should work -
var htmlarr = [];
$("input[type='radio'][name='radio123'],[type='radio'][id='radio123']").each(function () {
//any logic you need here
htmlarr.push($(this).clone().wrap('<div>').parent().html());
})
Demo - http://jsfiddle.net/tJ2Zc/
The code uses this method $(this).clone().wrap('<div>').parent().html() to get the outer HTML of a DOM element. More info can be found in the question - Get selected element's outer HTML
The code above writes all the radio button html into an array but you could change it to do what you wished within the loop.