HTML Change Within Jquery Textarea Value - javascript

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>

Related

How to add new line on JS append html

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>

From fetch request to DOM: How to convert the response into a walkable DOM structure? [duplicate]

Is there a way to convert HTML like:
<div>
<span></span>
</div>
or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().
Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript. There is no HTML content in the document.
You can use a DOMParser, like so:
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link
You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:
var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><span></span></div>';
var div= wrapper.firstChild;
If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.
But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.
Why not use insertAdjacentHTML
for example:
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here
Check out John Resig's pure JavaScript HTML parser.
EDIT: if you want the browser to parse the HTML for you, innerHTML is exactly what you want. From this SO question:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
Okay, I realized the answer myself, after I had to think about other people's answers. :P
var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);
Here is a little code that is useful.
var uiHelper = function () {
var htmls = {};
var getHTML = function (url) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="url" type="string">The url to the file with the HTML</param>
if (!htmls[url])
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
htmls[url] = xmlhttp.responseText;
};
return htmls[url];
};
return {
getHTML: getHTML
};
}();
--Convert the HTML string into a DOM Element
String.prototype.toDomElement = function () {
var wrapper = document.createElement('div');
wrapper.innerHTML = this;
var df= document.createDocumentFragment();
return df.addChilds(wrapper.children);
};
--prototype helper
HTMLElement.prototype.addChilds = function (newChilds) {
/// <summary>Add an array of child elements</summary>
/// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
/// <returns type="this" />
for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
return this;
};
--Usage
thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();
Just give an id to the element and process it normally eg:
<div id="dv">
<span></span>
</div>
Now you can do like:
var div = document.getElementById('dv');
div.appendChild(......);
Or with jQuery:
$('#dv').get(0).appendChild(........);
You can do it like this:
String.prototype.toDOM=function(){
var d=document
,i
,a=d.createElement("div")
,b=d.createDocumentFragment();
a.innerHTML=this;
while(i=a.firstChild)b.appendChild(i);
return b;
};
var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);
Alternatively, you can also wrap you html while it was getting converted to a string using,
JSON.stringify()
and later when you want to unwrap html from a html string, use
JSON.parse()

How to extract an array of all HTML tags from a textbox using javascript

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)

How to get dynamically loaded HTML tags with specific class from the page using JavaScript?

I am adding some HTML tags using JavaScript like this:
function createTag(text) {
if (text != '') {
text = text.replace(',', '');
if (/^\s+$/.test(text) == false) {
var tag = $('<div class="tags">' + text + '<a class="delete">X</a></div>');
tag.insertBefore($('input.tag_list'), $('input.tag_list'));
$('input.tag_list').val('');
}
}
I want to get the values in the <div class="tags"> tags from all over the page. How can I do it?
Also how can I restrict the number of dynamically created tags of these types?
Select the tags and use the map() function to return an array. Within the function supplied to map() remove the a from a cloned tag.
var tags = $(".tags").map(function(){
var clone = $(this).clone();
$(clone).find("a").remove("a");
return clone.text();
});
JS Fiddle: http://jsfiddle.net/ELxW4/
You could make life somewhat easier by wrapping the values in span tags:
<div class="tags"><span>javascript</span><a class="delete">X</a></div>
<div class="tags"><span>java</span><a class="delete">X</a></div>
<div class="tags"><span>jquery</span><a class="delete">X</a></div>
Then get the tags using:
var tags = $(".tags").map(function(){
return $(this).find("span").text();
});

How to add html element to the current textarea value, and output it as raw html

I need to style the total cost for user added in a textarea.
I have this fragment of code:
$("#student_teacher_profile_for_teaching_amount").keyup(function(e) {
var new_str, price, regex, str;
regex = /[0-9]+\.[0-9]{1,2}|[0-9]/;
str = $(this).val();
console.log(str);
price = str.match(regex);
if(price) {
if( $("#to_teach_ammount").length > 0 ) {
$("#to_teach_ammount").html(price[0]);
} else {
new_str = str.replace(regex, "<span id='to_teach_ammount'>" + price[0] + "</span>");
$(this).val(new_str);
}
$("#to_teach_total").val(price[0]); #this is and hiddent input filed
}
});
As a result of it I get:
some text before numbers <span id='to_teach_ammount'>2</span>
in my textarea.
How can I convert this into raw HTML?
This is not possible with a common <textarea> element, which only accepts plain text. You will have to use a (rich-text)-plugin, for example with jQuery. Have a look here: http://www.strangeplanet.fr/work/jquery-highlighttextarea/
The to_teach_total should not be a textarea. Instead it should be an element which expects html
Then use $(this).html(new_str) to set html
This html() method can also be passed a function which can take old html as parameter and return a new string to be set as new html

Categories