I have some node list, and I am trying to get some values from this list.
It works fine but I can't append the values in new lines and everything rendered together.
<div class="newinsert"></div>
<script>
const indiv = document.querySelector('.newinsert')
const flist = document.querySelectorAll('someclass')
const listClean = [...flist]
console.log(listClean);
listClean.forEach(list=> {
const html = `${list.innerHTML} `
indiv.append(html)
})
</script>
I tried adding <br> on html var but it just prints <br> with ""
\n doesn't work too
Thanks in advance.
EDIT: ok fixed it by
indiv.insertAdjacentHTML('beforeend', ${html} < br >)
append function receive string or HTMLNode element (more info)
but if your purpose is just to learn,you can simply replace InnerHtml content with your Html;
or concatenate it to the current content;
const indiv = document.querySelector('.newinsert')
const flist = document.querySelectorAll('someclass')
const listClean = [...flist]
console.log(listClean);
listClean.forEach(list=> {
const html = `${list.innerHTML}<br> `
indiv.innerHTML = html
//or
indiv.innerHTML = indiv.innerHTML+html // if you effectly want to append conent to current dev content
})
<div class="newinsert"></div>
Related
I have two textareas and I like to switch the content of these, so content of the first textarea shall be the content of the second textarea and vice versa. Following code just copy the content of the first textarea into the second, but the second step is not performed, so both textareas comprise the same content afterwards. No error occurs.
function switch_text_content(){
var src_text_memory = src_form.src_message.value;
var trgt_text_memory = trgt_form.trgt_message.value;
console.log(src_text_memory);
src_form.src_message.innerHTML = trgt_text_memory;
trgt_form.trgt_message.innerHTML = src_text_memory;
//switch_text_content2(trgt_text_memory);
}
You are doing in wrong way because you are using .innerHTML to set value instead you can to use .value property to set value of textarea. Like Below Example:
const switchBtn = document.querySelector('#switch-btn');
const firstTextarea = document.querySelector('#first-textarea');
const secondTextarea = document.querySelector('#second-textarea');
switchBtn.addEventListener('click', function() {
const firstContent = firstTextarea.value;
const secondContent = secondTextarea.value;
firstTextarea.value = secondContent;
secondTextarea.value = firstContent;
});
<textarea id="first-textarea">First Content</textarea>
<textarea id="second-textarea">Second Content</textarea>
<br/>
<button type="button" id="switch-btn">Switch</button>
I Want the code to get the number the user has entered and display it on the screen. I know that its just a dumb mistake that I have made.
function run() {
const quest = document.getElementById('quest');
const data = quest.value;
const element = document.createElement('div').innerHTML = data
const store = document.getElementById('store');
store.appendChild(element)
}
body {
text-align: center;
}
<h1>Calucator</h1>
<input type="number" name="" id="quest">
<button onclick="run()">=</button>
<div id="store"></div>
As the comments in your question pointed - document.createElement('div').innerHTML = data is not a document node element
And use .textContent instead of .innerHTML - otherwise you'll introduce an XSS vulnerability.
function run() {
const quest = document.getElementById("quest");
const data = quest.value;
const yourElement = document.createElement("div");
yourElement.textContent = data
const store = document.getElementById("store");
store.appendChild(yourElement);
}
What i changed in the function?
I first create the element, and then set it's text content. Finally i append it to the element you wanted.
I want to extract html codes from a textarea value but failed.
I want to detect and replace images with textarea value.
Below is an example of what I want to do.
TEXTAREA
<textarea class="editor"><img src="x1"><img src="x2"></textarea>
The code below is an example of what I want to do, I know it's wrong.
var editor_images = $('.editor').val().find('img');
editor_images.each(function(key, value) {
$(this).attr('src','example');
});
If you want to replace multiple attributes or tags, then your question may be too broad. However, the example below gives you an idea of how to replace an image attribute within the textarea:
function replaceValueOfTextArea(searchAttr, replaceAttr, value) {
const editor = document.querySelector('.editor');
const imgs = editor.value.match(/<img[a-zA-Z0-9="' ]+>/g);
let textAreaNewValue = '';
for (let img of imgs) {
const regMatch = new RegExp(`(?<!img)${searchAttr}`, "gi");
const match = img.match(regMatch);
if (match) {
const regAttr = new RegExp(`${searchAttr}=["|'][^"|']+["|']`, "gi");
textAreaNewValue += img.replace(regAttr, `${replaceAttr}="${value}"`);
} else {
textAreaNewValue += img;
}
}
editor.value = String(textAreaNewValue);
}
replaceValueOfTextArea('src', 'src', 'https://example.com');
<textarea class="editor"><img src="x1"><img alt="x2"></textarea>
You can use jQuery's $.parseHTML() to parse an HTML string into DOM nodes. Then you can use this method to turn them back into HTML before reinserting them in your <textarea>:
// Get contents of editor as HTML and parse into individual <img> nodes:
let nodes = $.parseHTML( $('.editor').val() )
// Map through <img> nodes and change src attribute, and return as HTML text:
let html = nodes.map(function(node){
$(node).attr('src', 'example')
return $('<div>').append($(node).clone()).html();
})
// Insert HTML text back into editor:
$('.editor').html( html.join('') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="editor"><img src="x1"><img src="x2"></textarea>
I'm looking to convert a string of content into a list separated by ",".
The content should be inserted in a textbox by the user.
This is my html:
<textarea id="csv_text" onkeyup=""></textarea>
<input onclick="convert_to_list()" value="Konvertera" type="button"/>
</fieldset>
</form>
<div id="converted_list">
And this is the Javascript that I try to make work, but I can't get my head around it:
function convert_to_list() {
var inputText= document.getElementById("csv_text").value;
var inputText = input.split(",");
document.getElementById("converted_list").innerHTML;
}
What am I doing wrong!?
You need to iterate the created array and create a new div with the list item as content.
function convert_to_list() {
var inputText= document.getElementById("csv_text").value;
var splittedText = inputText.split(",");
var anchor = document.getElementById("converted_list");
splittedText.forEach(text => {
var listItem = document.createElement("div")
listItem.innerText = text
anchor.appendChild(listItem)
})
}
In Java (since question is also marked with Java tag):
From text to list1:
List<String> convertToList(String text) {
return Arrays.asList(text.split(",",-1));
}
From list to text:
String convertToText(List<String> list) {
return String.join(",", list);
}
1: structure (size) of returned list cannot be changed - add new ArrayList<>(...) to create a fully modifiable list
I want to extract all the HTML tags like from this <body id = "myid"> .... </body> i just want to extract <body id ="myid"> similarly i want to extract all the HTML tags with attributes and using javascript.
I've tried using regex to make an array of all the tags inclosed between '< & >'
<script>
$(document).ready(function(){
// Get value on button click and show alert
$("#btn_parse").click(function(){
var str = $("#data").val();
var arr = str.split(/[<>]/);
$('#result').text(arr);
});
});
</script>
but it's creating an array arr containing empty and garbage also it's removing angular brackets '<>'
which I don't want.
SO in nutshell I want a script that takes
str ='mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...';
and produces an array like:
arr = ["<htmltag id='myid' class='myclass'>","</htmltag>",...];
Here is one dirty way. Add it to the dom so it can be accessed via normal DOM functions, then remove the text, and split the tags and push to an array.
str ="mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...";
div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
tags = div.querySelectorAll("*");
stripped = [];
tags.forEach(function(tag){
tag.innerHTML = "";
_tag = tag.outerHTML.replace("></",">~</");
stripped.push(_tag.split("~"));
});
console.log(stripped);
document.body.removeChild(div);
Assuming you can also get the input from a "live" page then the following should do what you want:
[...document.querySelectorAll("*")]
.map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
The above will combine the beginning and end tags into one string like
<div class="js-ac-results overflow-y-auto hmx3 d-none"></div>
And here is the same code applied on an arbitrary string:
var mystring="<div class='all'><htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag><p>another paragraph</p></div>";
const div=document.createElement("div");
div.innerHTML=mystring;
let res=[...div.querySelectorAll("*")].map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
console.log(res)